python中counter()记数,,一:定义一个list


一:定义一个list数组,求数组中每个元素出现的次数

如果用Java来实现,是一个比较复杂的,需要遍历数组list。

但是Python很简单:看代码

[python] view plain copya=[1,4,2,3,2,3,4,2]fromcollectionsimportCounterprintCounter(a)


打印结果:

Counter({2: 3, 3: 2, 4: 2, 1: 1})

结果表示:元素2出现了3次;元素3出现了2次;元素4出现了2次;元素1出现了1次。

二:求数组中出现次数最多的元素

直接看代码:

[python] view plain copy a=[1,4,2,3,2,3,4,2]fromcollectionsimportCounterprintCounter(a).most_commo(1)


运行结果:

[(2, 3)]

继续修改代码:

[python] view plain copy a=[1,4,2,3,2,3,4,2]fromcollectionsimportCounterprintCounter(a)printCounter(a).most_common(2)


运行结果:

[(2, 3), (3, 2)]

三:总结

(1)从Collections集合模块中引入集合类Counter

(2)Counter(a)可以打印出数组a中每个元素出现的次数

(3)Counter(a).most_common(2)可以打印出数组中出现次数最多的元素。参数2表示的含义是:输出几个出现次数最多的元素。

转自:http://blog.csdn.net/u013628152/article/details/43198605

python中counter()记数

评论关闭