【2.1.4】python列表--查找集合中重复元素的个数(count)
1. count
>>> 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)))
the 1 has found 1
the 2 has found 4
the 3 has found 3
the 4 has found 4
2. Counter
>>> from collections import Counter
>>> Counter([1,2,2,2,2,3,3,3,4,4,4,4])
Counter({2: 4, 4: 4, 3: 3, 1: 1})
如果输出数量最多的4个元素,可以
high_common = Counter([1,2,2,2,2,3,3,3,4,4,4,4]).most_common(4)
3.dict
data = [1,2,3,4,2,3,4,2,3,4,5,6,6,4,4,5,6,7,4]
data_dict = {}
for key in data:
data_dict[key] = data_dict.get(key,0) + 1
print("data_dict:",data_dict)
输出结果:
data_dict: {1: 1, 2: 3, 3: 3, 4: 6, 5: 2, 6: 3, 7: 1}
4. pd.value_counts
import pandas as pd
data = [1,2,3,4,2,3,4,2,3,4,5,6,6,4,4,5,6,7,4]
result = pd.value_counts(data)
print("result:",result)
输出结果:
result: 4 6
6 3
3 3
2 3
5 2
7 1
1 1
dtype: int64
参考资料
这里是一个广告位,,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn