Python 列表與字典:十個核心技巧與經(jīng)典案例
在Python編程世界中,列表和字典是最常用的兩大核心數(shù)據(jù)結(jié)構(gòu)。調(diào)查顯示,超過87%的日常數(shù)據(jù)處理場景都可以通過它們高效解決。列表如同有序的智能貨架,能容納各種數(shù)據(jù)類型;字典則像帶目錄的萬能檔案柜,實現(xiàn)閃電般的數(shù)據(jù)檢索。掌握它們的經(jīng)典用法,意味著你能:
- 高效處理CSV/JSON數(shù)據(jù)
- 快速實現(xiàn)數(shù)據(jù)分組統(tǒng)計
- 輕松構(gòu)建復(fù)雜數(shù)據(jù)結(jié)構(gòu)
- 避免無效循環(huán)提升性能

1. 列表的五大經(jīng)典用法與案例
(1) 數(shù)據(jù)過濾:列表推導(dǎo)式
# 過濾大于10的數(shù)字
numbers = [5, 17, 8, 22, 3]
filtered = [x for x in numbers if x > 10]
print(filtered) # [17, 22] [1](2) 動態(tài)分頁:高級切片
# 100條數(shù)據(jù)模擬數(shù)據(jù)庫查詢
dataset = [f"item_{i}" for i in range(1, 101)]
page_size, page_num = 10, 3
page_data = dataset[(page_num-1)*page_size : page_num*page_size]
print(f"第{page_num}頁:", page_data)
# 輸出:第3頁:['item_21', 'item_22', ..., 'item_30'] [1](3) 多維處理:嵌套列表
# 矩陣運算
matrix = [[1, 2], [3, 4]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transpose) # [[1, 3], [2, 4]] [1](4) 聚合統(tǒng)計:內(nèi)置方法
# 銷售數(shù)據(jù)分析
sales = [120, 85, 230, 145, 90]
max_sale = max(sales)
min_sale = min(sales)
total = sum(sales)
print(f"最高:{max_sale},最低:{min_sale},總額:{total}")
# 最高:230,最低:85,總額:670 [1](5) 并行處理:zip函數(shù)
# 同時遍歷姓名和分?jǐn)?shù)
names = ["Alice", "Bob", "Charlie"]
scores = [88, 92, 79]
for name, score in zip(names, scores):
print(f"{name}: {score}/100")
"""
Alice: 88/100
Bob: 92/100
Charlie: 79/100
""" [1]2. 字典的五大核心技巧與案例
(6) 安全訪問:get()方法
# 避免KeyError崩潰
user = {"name": "Alice", "age": 30}
print("城市:", user.get("city", "未知"))
# 城市: 未知 [2](7) 數(shù)據(jù)轉(zhuǎn)換:字典推導(dǎo)式
# 商品列表轉(zhuǎn)字典
products = [
("mouse", 89.9),
("keyboard", 199),
("monitor", 1299)
]
product_dict = {name: price for name, price in products}
print(product_dict)
# {'mouse': 89.9, 'keyboard': 199, 'monitor': 1299} [1][2](8) 分組統(tǒng)計:setdefault
# 按部門分組員工
employees = [
{"name": "Alice", "dept": "HR"},
{"name": "Bob", "dept": "IT"},
{"name": "Charlie", "dept": "HR"}
]
dept_groups = {}
for emp in employees:
dept_groups.setdefault(emp["dept"], []).append(emp["name"])
print(dept_groups)
# {'HR': ['Alice', 'Charlie'], 'IT': ['Bob']} [1](9) 復(fù)雜排序:key參數(shù)
# 按溫度降序排列城市
cities = [
{"name": "北京", "temp": 32},
{"name": "上海", "temp": 36},
{"name": "廣州", "temp": 35}
]
sorted_cities = sorted(cities, key=lambda x: x["temp"], reverse=True)
for city in sorted_cities:
print(f"{city['name']}: {city['temp']}℃")
"""
上海: 36℃
廣州: 35℃
北京: 32℃
""" [1](10) 高效統(tǒng)計:Counter神器
from collections import Counter
# 統(tǒng)計網(wǎng)站點擊來源
clicks = ["Google", "Direct", "Google", "Bing", "Facebook", "Google"]
click_counter = Counter(clicks)
print(click_counter.most_common(2))
# [('Google', 3), ('Direct', 1)] [1]3. 列表與字典綜合實戰(zhàn)案例
# 數(shù)據(jù)結(jié)構(gòu)定義
products = [
{"id": "P001", "name": "鼠標(biāo)", "stock": 42, "alert": 20},
{"id": "P002", "name": "鍵盤", "stock": 15, "alert": 30},
{"id": "P003", "name": "顯示器", "stock": 8, "alert": 10}
]
# 1. 生成需補貨的產(chǎn)品清單
needs_replenish = {
p["id"]: {"name": p["name"], "qty": p["alert"] - p["stock"]}
for p in products if p["stock"] < p["alert"]
}
print("需補貨商品:", needs_replenish)
# 輸出:{"P002": {"name": "鍵盤", "qty": 15}, "P003": {...}}
# 2. 安全更新庫存函數(shù)
def update_stock(product_list, update_data):
for p in product_list:
if p["id"] in update_data:
p["stock"] += update_data[p["id"]]["delivery"]
# 模擬到貨數(shù)據(jù)
deliveries = {"P003": {"delivery": 5}}
update_stock(products, deliveries)
# 3. 檢查更新后庫存
for p in products:
if p["id"] == "P003":
print(f"{p['name']}庫存已更新:{p['stock']}")
# 顯示器庫存已更新:13關(guān)鍵技術(shù)點:
- 字典推導(dǎo)式生成補貨清單
- 列表+字典嵌套實現(xiàn)結(jié)構(gòu)化數(shù)據(jù)
- 函數(shù)封裝確保更新安全
4. 終極避坑指南
(1) 可變陷阱:列表/字典作為參數(shù)傳遞時會被修改,重要數(shù)據(jù)需提前拷貝
import copy
original = [{"data": 1}]
safe_copy = copy.deepcopy(original) # ?(2) 鍵選擇原則:字典鍵必須可哈希,推薦使用字符串/元組
valid_dict = {("John", "Doe"): "value"} # ?
# invalid_dict = {["John", "Doe"]: "value"} # ?類型錯誤(3) 高效查找:字典查找為O(1),列表查找為O(n)
# 10萬條數(shù)據(jù)性能比較
big_list = list(range(100000))
big_dict = {i: f"item_{i}" for i in range(100000)}
# 字典查找快1000倍+
%timeit 99999 in big_list # 約1.3ms
%timeit 99999 in big_dict # 約0.03μs5. 提升進(jìn)階的四個秘訣
(1) 善用collections模塊:
- Counter用于頻次統(tǒng)計
- defaultdict避免鍵檢查
- OrderedDict保持插入順序
(2) 掌握字典視圖對象:
user = {"name": "Alice", "age": 30}
view = user.items() # 實時反映字典變化 [1](3) 列表優(yōu)先選推導(dǎo)式:
# 優(yōu)于顯式循環(huán)的寫法
cleaned = [x.strip() for x in data if x != ""](4) 擁抱JSON兼容性:
import json
json_str = json.dumps(my_dict) # 字典→JSON字符串 [1]正如Python之父Guido van Rossum所言:"列表和字典是Python的心臟。" 它們不僅承載數(shù)據(jù),更構(gòu)建了解決問題的思維框架。當(dāng)你能靈活組合這兩種結(jié)構(gòu)——比如列表中嵌套字典,字典值存儲列表——你將解鎖Python真正的數(shù)據(jù)處理超能力。


































