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]