概述
counter是一个计数器,帮助我们对某项数据进行计数,如计算每个人各喜欢多少种颜色
from collections import Counter
colors ={
('yasoob', 'Yellow'),
('Ali', 'blue'),
('Ali','black'),
('ali','white'),
('ahemd','silver'),
}
favs = Counter(name for name , color in colors)
print(favs)
找出出现频率最高的数字
list1 = [111,2222,3333,444,555,6,676766,355,35353,42,87,46,5,5,5,5,34343,33,33,3433,3434,878]
print(Counter(list1).most_common(2))
print(Counter(list1)[5]) #查看某个元素出现的次数
[(5, 4), (33, 2)]
还可以和 数学运算符 结合使用
list1 = [111,2222,3333,444,555,6,676766,355,35353,42,87,46,5,5,5,5,34343,33,33,3433,3434,878]
list2 = [6665555,555666]
h1 = Counter(list1)
h2 = Counter(list2)
print(h1 + h2)
print(h1 - h2)
from collections import defaultdict
lists = ['a', 'a', 'b', 5, 6, 7, 5]
count_dict = defaultdict(int)
for item in lists:
count_dict[item] += 1
print(count_dict)
list2 = [1,1,1,3,3,44,4,5,5,7,8,9,10]
a = Counter(list2)
print(type(a))
print(a)
print(a[5])
list3 = ['lala','koukou','beibei','lala','jj','koukou']
b = Counter(list3)
print(b)
print(b['lala'])
for key in b:
print(key)
统计计数的简单例子,易懂
最后
以上就是哭泣花瓣为你收集整理的counter的全部内容,希望文章能够帮你解决counter所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复