python 中 defaultdict 的用法

场景:统计一个字符串列表中每个字符串的频数。一个明显的方法是建立一个键是字符串,值是频数的字典。

方法1:

word_count={}
for word in document:
    if word in word_count:
        word_count[word]+=1
    else:
        word_count[word]=1

方法2:

word_count={}
for word in document:
    try:
        word_count[word]+=1
    except KeyError:
        word_count[word]=1

方法3:

word_count={}
for word in document:
    previous_count=word_count.get(word,0)
    word_count[word]=previous_count+1

以上三种方法都略显笨拙,这是defaultdict的意义所在

defaultdict会在你查找一个没有包含在内的键时,提供一个零参数函数建立一个新的键,并为它的值增加1

方法4:

from collections import defaultdict
word_count=defaultdict(int) #int()生成0
for word in document:
    word_count[word]+=1

该函数对列表,字典或自定义函数都有用:

dd_list=defaultdict(list) #list生成一个空列表

dd_list[2].append(1)#现在dd_list包含{2:[1]}

 

dd_dict=defaultdict(dict)#dict生成一个空的字典

dd_dict['joel']['city']='seattle'#现在dd_dict包含{‘joel’:{'city':'seattle'}}

 

dd_pair=defaultdict(lambda:[0,0])

dd_pair[2][1]=1#现在dd_pair包含{2:[0,1]}

 

嗯,其实吧,还有一个更简单的方法:

from collections import Counter
word_count=Counter(document)

Counter实例带有的most_common方法也比较常用

#显示10个最常见的词和相应的计数:

for word,count in word_count.most_common(10):

    print word,count

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值