Python 统计列表中重复项

对一个列表,比如[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})

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×