python 判断列表中每个元素有几个

使用标准库提供的collections

基本用法:

 

import collections
lst = []    # lst存放所谓的100万个元素
d = collections.Counter(lst)
# 瞬间出结果
for k in d:
    # k是lst中的每个元素
    # d[k]是k在lst中出现的次数

 



from collections import 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'
]



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

 参考:点击打开链接

 

 

 

你可能感兴趣的:(Python高效数据分析)