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).


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM