使用collections.Counter 统计列表中元素出现的频率

通常想要统计一个列表中的元素出现频率得使用创建字典建立索引再遍历列表的方式来实现。

但是使用collections.Counter 可以很便捷的给出结果,也可以对结果进行排序

from collections import Counter
data = [randint(0,20) for _ in range(30)]
c2 = Counter(data)
c2
Counter({7: 3,
         1: 1,
         2: 1,
         12: 2,
         16: 3,
         0: 1,
         4: 2,
         5: 4,
         8: 2,
         17: 1,
         15: 3,
         10: 1,
         11: 1,
         9: 1,
         20: 1,
         13: 2,
         6: 1})
c2.most_common(3)
[(5, 4), (7, 3), (16, 3)]

 

你可能感兴趣的:(Python)