
Python编程中经常遇到的问题,如何统计一个列表中重复项?总结如下:
方法1:
1 2 3 4
|
test_list = [1,2,2,3,3,3,4,4,4,4] test_set = set(test_list) for item in test_set: print("the %d has found %d" %(item,test_list.count(item)))
|
方法2:
利用字典的特性来实现。
1 2 3 4 5 6
|
List=[1,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)
|
方法3:
1 2
|
from collections import Counter Counter([1,2,2,3,3,3,4,4,4,4])
|
近期评论