# -*- coding: utf-8 -*-
# 要统计的词
words = ["腾讯", "百度", "阿里巴巴", "百度", "阿里巴巴"]
# 方式一:使用dict方式
counter1 = {}
for word in words:
counter1[word] = counter1.get(word, 0) + 1
print(counter1)
# {'腾讯': 1, '百度': 2, '阿里巴巴': 2}
# 方式二:使用defaultdict
from collections import defaultdict
counter2 = defaultdict(lambda: 0)
for word in words:
counter2[word] += 1
print(counter2)
# defaultdict(,
# {'腾讯': 1, '百度': 2, '阿里巴巴': 2})
参考: python中defaultdict方法的使用