元素出现次数统计

如何查找序列中出现次数最多的元素或者说如何统计序列中元素的出现次数.

也会你会想到遍历,建立字典,计数…..

但是今天要告诉你的是,其实这些工作都不用自己做,Collections.Counter类就是为这种需求量身定做的.

看代码:

>>>words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes','the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the','eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into','my', 'eyes', "you're", 'under']
>>>from collections import Counter
>>>word_count=Counter(words)

>>>word_count
Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, "don't": 1, "you're": 1, 'under': 1})
>>>word_count.most_common(2)
[('eyes', 8), ('the', 5)]

轻而易举,将word的词都进行了词頻统计,而且可以调用most_common()函数输出频率最高的词.

如果这个时候又有一个新的词库,需要添加进去,也好办:

>>>new_word=['why','are','you','not','looking','in','my','eyes']
>>>word_count.update(new_word)
>>>word_count
Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2, 'around': 2, "don't": 1, "you're": 1, 'under': 1, 'why': 1, 'are': 1, 'you': 1, 'looking': 1, 'in': 1})
>>>word_count.most_common(2)
[('eyes', 9), ('the', 5)]

依然很简单就对词频统计进行了更新.

关于Counter对象,还有一个很多人都忽视的点,那就是它与算术运算的结合:

>>>words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes','the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the','eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into','my', 'eyes', "you're", 'under']
>>>new_word=['why','are','you','not','looking','in','my','eyes']
>>>from collections import Counter
>>>a=Counter(words)
>>>b=Counter(new_word)
>>>a+b
Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2, 'around': 2, "don't": 1, "you're": 1, 'under': 1, 'why': 1, 'are': 1, 'you': 1, 'looking': 1, 'in': 1})

>>>a-b
Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, "don't": 1, "you're": 1, 'under': 1})
>>>b-a
Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, "don't": 1, "you're": 1, 'under': 1})

Counter 对象可以接受任意的由可哈希(hashable)元素构成的序列对象。 在底层实现上,一个 Counter 对象就是一个字典,将元素映射到它出现的次数上.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值