Python中defaultdict用法

2018-06-08  本文已影响32人  致Great
strings = ('puppy', 'kitten', 'puppy', 'puppy',
           'weasel', 'puppy', 'kitten', 'puppy')
counts = {}
"""
    单词统计
"""
# 方法1 使用判断语句检查
for word in strings:
    if word not in counts:
        counts[word] = 1
    else:
        counts[word] += 1
print(counts)

# 方法2 使用dict.setdefault()方法来设置默认值:
counts = {}
for word in strings:
    counts.setdefault(word, 0)
    counts[word] += 1
print(counts)

# 方法3 使用collections.defaultdict
from collections import defaultdict
counts = defaultdict(lambda: 0)
for word in strings:
    counts[word] += 1
print(counts)

结果:

{'puppy': 5, 'kitten': 2, 'weasel': 1}
{'puppy': 5, 'kitten': 2, 'weasel': 1}
defaultdict(<function <lambda> at 0x0000000001D12EA0>, {'puppy': 5, 'kitten': 2, 'weasel': 1})
[Finished in 0.1s]

更多:
https://www.cnblogs.com/jidongdeatao/p/6930325.html

上一篇 下一篇

猜你喜欢

热点阅读