collections.Counter类统计列表元素出现次数

# 使用collections.Counter类统计列表元素出现次数

 1 from collections import Counter
 2 
 3 
 4 names = ["Stanley", "Lily", "Bob", "Well", "Peter", "Bob", "Well", "Peter", "Well", "Peter", "Bob",
 5     "Stanley", "Lily", "Bob", "Well", "Peter", "Bob", "Bob", "Well", "Peter", "Bob", "Well"]
 6 
 7 names_counts = Counter(names)  # 实例化Counter对象,可接收任何hashable序列,Counter对象可以像字典一样访问元素并返回出现的次数
 8 print(names_counts["Stanley"])
 9 # 2
10 print(names_counts)
11 # Counter({'Bob': 7, 'Well': 6, 'Peter': 5, 'Stanley': 2, 'Lily': 2})
12 
13 top_three = names_counts.most_common(3)  # 取出出现次数最多的三个元素
14 print(top_three)
15 # [('Bob', 7), ('Well', 6), ('Peter', 5)]
16 
17 more_names = ["Stanley", "Lily", "Bob", "Well"]
18 names_counts.update(more_names)  # 使用update方法新增需要统计的序列
19 top_three = names_counts.most_common(3)  # 取出出现次数最多的三个元素
20 print(top_three)
21 # [('Bob', 8), ('Well', 7), ('Peter', 5)]
22 
23 names_counts = Counter(names)
24 more_names_counts = Counter(more_names)
25 print(names_counts)
26 # Counter({'Bob': 7, 'Well': 6, 'Peter': 5, 'Stanley': 2, 'Lily': 2})
27 print(more_names_counts)
28 # Counter({'Stanley': 1, 'Lily': 1, 'Bob': 1, 'Well': 1})
29 print(names_counts - more_names_counts) # 减去次数
30 # Counter({'Bob': 6, 'Well': 5, 'Peter': 5, 'Stanley': 1, 'Lily': 1})
31 print(names_counts + more_names_counts) # 合并次数
32 # Counter({'Bob': 8, 'Well': 7, 'Peter': 5, 'Stanley': 3, 'Lily': 3})

参考资料:
  Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).

参考资料:
  Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).

猜你喜欢

转载自www.cnblogs.com/hycstar/p/9345751.html