python学习——Counter计数方法

来源:互联网 发布:淘宝店铺改名字 编辑:程序博客网 时间:2024/06/07 01:25

1、统计一个序列中元素的次数:

from collections import Countera = [10, 8, 6, 7, 2, 8, 4, 10, 3, 7, 8, 4, 5, 7, 2, 2, 3, 8, 8, 9, 6, 2, 2, 7, 8, 7, 4, 8, 5, 2]b = Counter(a)print(b)

得到结果:

Counter({8: 7, 2: 6, 7: 5, 4: 3, 10: 2, 6: 2, 3: 2, 5: 2, 9: 1})

2、如果想要得到排名前几的话:

from collections import Countera = [10, 8, 6, 7, 2, 8, 4, 10, 3, 7, 8, 4, 5, 7, 2, 2, 3, 8, 8, 9, 6, 2, 2, 7, 8, 7, 4, 8, 5, 2]b = Counter(a).most_common(3)print(b)

得到结果:

[(8, 7), (2, 6), (7, 5)]

3、总结
(1)从collections集合模块中引入集合类Counter
(2)Counter(a)可以打印出数组a中每个元素出现的次数
(3)Counter(a).most_common(2)可以打印出数组中出现次数最多的元素。参数2表示的含义是:输出几个出现次数最多的元素。

原创粉丝点击