Python编程:使用defaultdict统计词频

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

参考:
python中defaultdict方法的使用


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部