Counter() most_common()

1 不仅可以统计list中元素的出现次数,也可以对str中的元素进行统计

# collections包中的Counter用于统计str list 中元素出现次数
from collections import Counter
a = [1,1,2,3,4,5,6,6,6]
b = Counter(a)
# 输出一个a中每个元素出现次数的类,且按出现次数由高到低排列
print(b)
# 输出元素5的出现次数
print(b[5])
# 输出出现次数前三的(元素,次数)对,且类型是list
print(b.most_common(3))
# Counter({6: 3, 1: 2, 2: 1, 3: 1, 4: 1, 5: 1})
# 1
# [(6, 3), (1, 2), (2, 1)]


# 如下直接输出元素按出现次数由高到低的排序,用的most_common()目的是将Counter(a)化为list,便于迭代
print([item for items, c in Counter(a).most_common() for item in [items] * c])
# [6, 6, 6, 1, 1, 2, 3, 4, 5]
View Code

参考:http://www.aiisen.com/p/1166376.html

猜你喜欢

转载自www.cnblogs.com/xxswkl/p/11988500.html