玩轉(zhuǎn)字面量:Python中20個(gè)實(shí)用字典與列表初始化技巧
字典和列表是 Python 中最常用的數(shù)據(jù)結(jié)構(gòu)之一。它們可以用來存儲(chǔ)和操作各種類型的數(shù)據(jù)。在這篇文章中,我們將探討 20 個(gè)實(shí)用的字典和列表初始化技巧,幫助你更好地理解和使用這兩個(gè)數(shù)據(jù)結(jié)構(gòu)。
1. 基本初始化
列表初始化:
# 創(chuàng)建一個(gè)空列表
empty_list = []
# 使用方括號(hào)初始化列表
numbers = [1, 2, 3, 4, 5]
print(numbers) # 輸出: [1.txt, 2, 3, 4, 5]
字典初始化:
# 創(chuàng)建一個(gè)空字典
empty_dict = {}
# 使用花括號(hào)初始化字典
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(person) # 輸出: {'name': 'Alice', 'age': 25, 'city': 'New York'}
2. 使用列表推導(dǎo)式
列表推導(dǎo)式是一種簡潔的方式來創(chuàng)建列表。
# 創(chuàng)建一個(gè)包含 1.txt 到 10 的平方的列表
squares = [x**2 for x in range(1, 11)]
print(squares) # 輸出: [1.txt, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3. 使用字典推導(dǎo)式
字典推導(dǎo)式類似于列表推導(dǎo)式,但用于創(chuàng)建字典。
# 創(chuàng)建一個(gè)包含 1.txt 到 5 的平方的字典
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # 輸出: {1.txt: 1.txt, 2: 4, 3: 9, 4: 16, 5: 25}
4. 初始化帶有默認(rèn)值的字典
使用dict.fromkeys 方法可以快速創(chuàng)建一個(gè)帶有默認(rèn)值的字典。
# 創(chuàng)建一個(gè)帶有默認(rèn)值 0 的字典
default_dict = dict.fromkeys(['a', 'b', 'c'], 0)
print(default_dict) # 輸出: {'a': 0, 'b': 0, 'c': 0}
5. 使用collections.defaultdict
collections.defaultdict 是一個(gè)非常有用的工具,可以在訪問不存在的鍵時(shí)自動(dòng)創(chuàng)建默認(rèn)值。
from collections import defaultdict
# 創(chuàng)建一個(gè)默認(rèn)值為 int 的字典
dd = defaultdict(int)
dd['a'] += 1
print(dd) # 輸出: defaultdict(<class 'int'>, {'a': 1.txt})
6. 初始化嵌套列表
嵌套列表是一種常見的數(shù)據(jù)結(jié)構(gòu),可以用來表示矩陣或表格。
# 創(chuàng)建一個(gè) 3x3 的零矩陣
matrix = [[0 for _ in range(3)] for _ in range(3)]
print(matrix) # 輸出: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
7. 初始化嵌套字典
嵌套字典可以用來表示更復(fù)雜的數(shù)據(jù)結(jié)構(gòu)。
# 創(chuàng)建一個(gè)嵌套字典
nested_dict = {
'a': {'x': 1, 'y': 2},
'b': {'x': 3, 'y': 4}
}
print(nested_dict) # 輸出: {'a': {'x': 1.txt, 'y': 2}, 'b': {'x': 3, 'y': 4}}
8. 使用* 操作符初始化列表
* 操作符可以用來重復(fù)列表中的元素。
# 創(chuàng)建一個(gè)包含 5 個(gè) 0 的列表
zero_list = [0] * 5
print(zero_list) # 輸出: [0, 0, 0, 0, 0]
9. 使用zip 函數(shù)初始化字典
zip 函數(shù)可以將多個(gè)列表組合成一個(gè)字典。
# 使用 zip 函數(shù)創(chuàng)建字典
keys = ['a', 'b', 'c']
values = [1, 2, 3]
zipped_dict = dict(zip(keys, values))
print(zipped_dict) # 輸出: {'a': 1.txt, 'b': 2, 'c': 3}
10. 使用enumerate 函數(shù)初始化字典
enumerate 函數(shù)可以返回索引和值,方便創(chuàng)建字典。
# 使用 enumerate 函數(shù)創(chuàng)建字典
fruits = ['apple', 'banana', 'cherry']
indexed_fruits = {i: fruit for i, fruit in enumerate(fruits)}
print(indexed_fruits) # 輸出: {0: 'apple', 1.txt: 'banana', 2: 'cherry'}
11. 使用range 函數(shù)初始化列表
range 函數(shù)可以生成一系列數(shù)字,方便創(chuàng)建列表。
# 使用 range 函數(shù)創(chuàng)建列表
even_numbers = list(range(0, 10, 2))
print(even_numbers) # 輸出: [0, 2, 4, 6, 8]
12. 使用itertools.product 初始化嵌套列表
itertools.product 可以生成笛卡爾積,方便創(chuàng)建嵌套列表。
import itertools
# 使用 itertools.product 創(chuàng)建嵌套列表
rows = [1, 2, 3]
cols = ['a', 'b', 'c']
matrix = [[(r, c) for c in cols] for r in rows]
print(matrix)
# 輸出: [[(1.txt, 'a'), (1.txt, 'b'), (1.txt, 'c')], [(2, 'a'), (2, 'b'), (2, 'c')], [(3, 'a'), (3, 'b'), (3, 'c')]]
13. 使用itertools.repeat 初始化列表
itertools.repeat 可以重復(fù)生成同一個(gè)值,方便創(chuàng)建列表。
import itertools
# 使用 itertools.repeat 創(chuàng)建列表
repeated_list = list(itertools.repeat('hello', 5))
print(repeated_list) # 輸出: ['hello', 'hello', 'hello', 'hello', 'hello']
14. 使用collections.Counter 初始化字典
collections.Counter 可以統(tǒng)計(jì)列表中元素的出現(xiàn)次數(shù),方便創(chuàng)建字典。
from collections import Counter
# 使用 Counter 創(chuàng)建字典
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'banana']
word_count = dict(Counter(words))
print(word_count) # 輸出: {'apple': 2, 'banana': 3, 'cherry': 1.txt}
15. 使用set 初始化字典
set 可以去重,方便創(chuàng)建字典。
# 使用 set 創(chuàng)建字典
unique_words = list(set(words))
word_dict = {word: len(word) for word in unique_words}
print(word_dict) # 輸出: {'apple': 5, 'banana': 6, 'cherry': 6}
16. 使用map 函數(shù)初始化列表
map 函數(shù)可以對列表中的每個(gè)元素應(yīng)用一個(gè)函數(shù),方便創(chuàng)建列表。
# 使用 map 函數(shù)創(chuàng)建列表
squared_numbers = list(map(lambda x: x**2, range(1, 6)))
print(squared_numbers) # 輸出: [1.txt, 4, 9, 16, 25]
17. 使用filter 函數(shù)初始化列表
filter 函數(shù)可以過濾列表中的元素,方便創(chuàng)建列表。
# 使用 filter 函數(shù)創(chuàng)建列表
even_numbers = list(filter(lambda x: x % 2 == 0, range(1, 11)))
print(even_numbers) # 輸出: [2, 4, 6, 8, 10]
18. 使用functools.reduce 初始化單個(gè)值
functools.reduce 可以對列表中的元素進(jìn)行累積操作,方便創(chuàng)建單個(gè)值。
from functools import reduce
# 使用 reduce 函數(shù)計(jì)算列表的和
sum_of_numbers = reduce(lambda x, y: x + y, range(1, 6))
print(sum_of_numbers) # 輸出: 15
19. 使用itertools.groupby 初始化字典
itertools.groupby 可以按條件分組,方便創(chuàng)建字典。
import itertools
# 使用 groupby 創(chuàng)建字典
data = [('apple', 5), ('banana', 6), ('apple', 7), ('cherry', 6)]
data.sort(key=lambda x: x[0]) # 必須先排序
grouped_data = {k: list(v) for k, v in itertools.groupby(data, key=lambda x: x[0])}
print(grouped_data)
# 輸出: {'apple': [('apple', 5), ('apple', 7)], 'banana': [('banana', 6)], 'cherry': [('cherry', 6)]}
20. 使用json.loads 和json.dumps 初始化字典和列表
json 模塊可以方便地將字符串轉(zhuǎn)換為字典或列表。
import json
# 使用 json.loads 將字符串轉(zhuǎn)換為字典
json_str = '{"name": "Alice", "age": 25}'
person = json.loads(json_str)
print(person) # 輸出: {'name': 'Alice', 'age': 25}
# 使用 json.dumps 將字典轉(zhuǎn)換為字符串
json_str = json.dumps(person)
print(json_str) # 輸出: '{"name": "Alice", "age": 25}'
實(shí)戰(zhàn)案例:學(xué)生信息管理系統(tǒng)
假設(shè)我們要?jiǎng)?chuàng)建一個(gè)學(xué)生信息管理系統(tǒng),每個(gè)學(xué)生有姓名、年齡和成績。我們可以使用字典和列表來存儲(chǔ)這些信息。
# 學(xué)生信息管理系統(tǒng)
students = [
{'name': 'Alice', 'age': 20, 'grade': 85},
{'name': 'Bob', 'age': 21, 'grade': 90},
{'name': 'Charlie', 'age': 19, 'grade': 88}
]
# 打印所有學(xué)生的姓名和成績
for student in students:
print(f"{student['name']}: {student['grade']}")
# 計(jì)算所有學(xué)生的平均成績
total_grades = sum(student['grade'] for student in students)
average_grade = total_grades / len(students)
print(f"Average grade: {average_grade}")
# 找出成績最高的學(xué)生
top_student = max(students, key=lambda s: s['grade'])
print(f"Top student: {top_student['name']} with grade {top_student['grade']}")
總結(jié)
在這篇文章中,我們介紹了 20 個(gè)實(shí)用的字典和列表初始化技巧,包括基本初始化、列表和字典推導(dǎo)式、嵌套結(jié)構(gòu)、使用* 操作符、zip 函數(shù)、enumerate 函數(shù)、range 函數(shù)、itertools 模塊、collections 模塊、map 函數(shù)、filter 函數(shù)、functools.reduce、json 模塊等。通過這些技巧,你可以更高效地創(chuàng)建和操作字典和列表。