元素出现次数统计

    xiaoxiao2021-03-25  60

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

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

    但是今天要告诉你的是,其实这些工作都不用自己做,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 对象就是一个字典,将元素映射到它出现的次数上.

    转载请注明原文地址: https://ju.6miu.com/read-36873.html

    最新回复(0)