对一个列表,比如[1,2,2,2,2,3,3,3,4,4,4,4],现在我要统计这个列表里的重复项,并且重复了几次也要统计出来。
重复项出现的次数
eg1
1 2 3 4
| mylist = [1,2,2,2,2,3,3,3,4,4,4,4] myset = set(mylist) for item in myset: print("the %d has found %d" %(item,mylist.count(item)))
|
eg2
1 2 3 4 5 6 7
| List=[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) #利用字典的特性来实现
|
eg3
1 2 3
| >>>from collections import Counter >>>Counter([1,2,2,2,2,3,3,3,4,4,4,4]) >>>Counter({1: 5, 2: 3, 3: 2})
|
列表中出现最多的项
eg1
1 2 3 4 5 6 7
| from collections import Counter a=['bj', 'bj', 'bj', 'gz', 'shh', 'shh'] d=Counter(a) print d print d.most_common() print d.most_common()[0] print d.most_common()[0][0]
|
eg2
1 2 3 4 5 6 7 8
| def sortbylistcount(self,list): cnt=0 city="" for x in list: if list.count(x)>cnt: city=x cnt=list.count(x) return city
|
eg3
1 2 3 4 5 6
| for n in a: old=a.count(n) num=max(a.count(m) for m in a) if num==old: print n break
|