📚 每日Python小知识 🐍
每天花1分钟,解锁一个Python实用技巧/冷知识!无论是新手还是老手,这里都有让你眼前一亮的编程干货。
博主出去度假了(不是故意不更新的)
✨ 今日主题:collections.defaultdict
💡 当键不存在时,自动提供默认值,告别KeyError!
from collections import defaultdict
# 传统字典:需要手动处理键不存在的情况
word_counts = {}
for word in ["apple", "banana", "apple", "cherry"]:
if word not in word_counts:
word_counts[word] = 0
word_counts[word] += 1
# 使用defaultdict:自动初始化默认值
word_counts = defaultdict(int) # 默认值为0
for word in ["apple", "banana", "apple", "cherry"]:
word_counts[word] += 1
print(word_counts) # 输出:{'apple': 2, 'banana': 1, 'cherry': 1}
✨ 进阶用法:
-
自定义默认值工厂:
# 默认值为空列表 graph = defaultdict(list) graph["A"].append("B") # 无需先初始化 -
统计复杂数据:
# 按类别分组 items = [("fruit", "apple"), ("fruit", "banana"), ("vegetable", "carrot")] categories = defaultdict(list) for category, item in items: categories[category].append(item)🚀 适用场景:
-
词频统计
-
图结构建模
-
数据分组聚合
你学会了吗?
857

被折叠的 条评论
为什么被折叠?



