Python说文解字_计数器
from collections import Counter response = [ "vanilla", "chocolate", "vanilla", "vanilla", "caramel", "strawberry", "vanilla" ] print("The children voted for {} ice cream". format(Counter(response).most_common(1)[0][0])) # The children voted for vanilla ice cream # most_common()中,用于只获取出现次数最多的元素,返回由(key,count)元组组成的列表按照计数排序。 # import collections obj = Counter('aabbccc') print(obj) #输出:Counter({'c': 3, 'a': 2, 'b': 2}) # elements() obj = Counter('aabbccc') print(sorted(obj.elements())) #输出:['a', 'a', 'b', 'b', 'c', 'c', 'c'] for k in obj.elements(): #遍历打印obj所有元素 print(k) # most_common(指定一个参数n,列出前n个元素,不指定参数,则列出所有) obj = Counter('aabbbcccc') print(obj.most_common()) # items(从dict类中继承的方法) obj = Counter('aabbbcccc') print(obj.items()) for k,v in obj.items(): print(k,v) #输出:dict_items([('b', 3), ('c', 4), ('a', 2)]) # b 3 # c 4 # a 2 #输出:[('c', 4), ('b', 3)] # update(增加元素) obj = Counter(['11','22']) obj.update(['22','55']) print(obj) #输出:Counter({'22': 2, '11': 1, '55': 1}) # subtract(原来的元素减去新传入的元素) obj = Counter(['11','22','33']) obj.subtract(['22','55']) print(obj) #输出:Counter({'11': 1, '33': 1, '22': 0, '55': -1})
from collections import Counter
response = [
"vanilla",
"chocolate",
"vanilla",
"vanilla",
"caramel",
"strawberry",
"vanilla"
]
print("The children voted for {} ice cream".
format(Counter(response).most_common(1)[0][0]))
# The children voted for vanilla ice cream
# most_common()中,用于只获取出现次数最多的元素,返回由(key,count)元组组成的列表按照计数排序。
# import collections
obj = Counter('aabbccc')
print(obj)
#输出:Counter({'c': 3, 'a': 2, 'b': 2})
# elements()
obj = Counter('aabbccc')
print(sorted(obj.elements()))
#输出:['a', 'a', 'b', 'b', 'c', 'c', 'c']
for k in obj.elements(): #遍历打印obj所有元素
print(k)
# most_common(指定一个参数n,列出前n个元素,不指定参数,则列出所有)
obj = Counter('aabbbcccc')
print(obj.most_common())
# items(从dict类中继承的方法)
obj = Counter('aabbbcccc')
print(obj.items())
for k,v in obj.items():
print(k,v)
#输出:dict_items([('b', 3), ('c', 4), ('a', 2)])
# b 3
# c 4
# a 2
#输出:[('c', 4), ('b', 3)]
# update(增加元素)
obj = Counter(['11','22'])
obj.update(['22','55'])
print(obj)
#输出:Counter({'22': 2, '11': 1, '55': 1})
# subtract(原来的元素减去新传入的元素)
obj = Counter(['11','22','33'])
obj.subtract(['22','55'])
print(obj)
#输出:Counter({'11': 1, '33': 1, '22': 0, '55': -1})
本博客所有文章仅用于学习、研究和交流目的,欢迎非商业性质转载。