Counter類:計算序列中出現次數最多的元素
1 from collections import Counter 2 3 c = Counter('abcdefaddffccef') 4 print('完整的Counter對象:', c) 5 6 a_times = c['a'] 7 print('元素a出現的次數:', a_times) 8 9 c_most = c.most_common(3) 10 print('出現次數最多的三個元素:', c_most) 11 12 times_dict = c.values() 13 print('各元素出現個數的列表:', times_dict) 14 15 total_times = sum(c.values()) 16 print("所有元素出現次數的總和:", total_times)
運行結果:
1 完整的Counter對象: Counter({'f': 4, 'c': 3, 'd': 3, 'a': 2, 'e': 2, 'b': 1}) 2 元素a出現的次數: 2 3 出現次數最多的三個元素: [('f', 4), ('c', 3), ('d', 3)] 4 各元素出現個數的列表: dict_values([2, 1, 3, 3, 2, 4]) 5 所有元素出現次數的總和: 15