Python 统计列表中重复项

本文最后更新于 2017年4月13日 下午

对一个列表,比如[1,2,2,2,2,3,3,3,4,4,4,4],要统计这个列表里的重复项,以及相应的次数。

有三种方法,set,dict以及Counter

第一种:

1
2
3
4
L = [1,2,2,2,2,3,3,3,4,4,4,4]
myset = set(L)
for item in myset:
print("the %d has found %d" %(item,L.count(item)))

第二种:

1
2
3
4
5
6
L = [1,2,2,2,2,3,3,3,4,4,4,4]
a = {}
for i in List:
if List.count(i)>1:
a[i] = List.count(i)
print (a)

第三种:

1
2
3
from collections import Counter
print Counter([1,2,2,2,2,3,3,3,4,4,4,4])
# Counter({1: 5, 2: 3, 3: 2})

Python 统计列表中重复项
https://yuluod.github.io/2017/04/13/Python-统计列表中重复项/
作者
yuluo
发布于
2017年4月13日
许可协议