collections的基本使用

Counter计数器

Counter 是一个字典子类,用于计数可哈希对象。可以用作计算词频。

from collections import Counter

# 统计字符出现次数
cnt = Counter('abracadabra')
print(cnt)
# Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

# 统计单词出现次数
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_cnt = Counter(words)
print(word_cnt.most_common(2))  # [('apple', 3), ('banana', 2)]

defaultdict:默认字典

defaultdict 是字典的子类,当访问不存在的键时,会返回一个默认值而不是抛出 KeyError。

from collections import defaultdict

# 默认值为int(即0)
dd = defaultdict(int)
dd['a'] += 1
print(dd['a'])  # 1
print(dd['b'])  # 0 (自动创建)

# 默认值为list
dd_list = defaultdict(list)
dd_list['colors'].append('red')
dd_list['colors'].append('blue')
print(dd_list)  # defaultdict(<class 'list'>, {'colors': ['red', 'blue']})
animals = [('猫', '橘猫'), ('狗', '金毛'), ('猫', '暹罗猫'), ('鸟', '鹦鹉'), ('狗', '哈士奇')]

animal_dict = defaultdict(list)
for category, name in animals:
    animal_dict[category].append(name)

print(dict(animal_dict))
# {'猫': ['橘猫', '暹罗猫'], '狗': ['金毛', '哈士奇'], '鸟': ['鹦鹉']}

使用 lambda 表达式自定义默认值

# 默认值为字符串 'N/A'
dd_str = defaultdict(lambda: 'N/A')
print(dd_str['name'])  # 'N/A'

# 默认值为固定值
dd_fixed = defaultdict(lambda: 3.14)
print(dd_fixed['pi'])  # 3.14
posted @ 2025-05-14 17:41  CodeCraftsMan  阅读(16)  评论(0)    收藏  举报