【集合】统计元素出现次数
from random import randint from collections import Counter import re ''' 统计元素出现的次数并打印出现次数最多的3个数字 ''' # 生成随机30个 1-20的随机数 l = [randint(1, 20) for i in range(0, 30)] print(l) # 生成1-20的key并将次数初始化0 d = {i: 0 for i in range(1, 21)} # 统计次数 print(d) for x in l: d[x] += 1 print(d) print('-' * 50) # 法1 使用collections Counter对象 print(Counter(d)) print(Counter(d).most_common(3)) s = 'May you have enough happiness to make you sweet,enough trials to make you' \ ' strong,enough sorrow to keep you human,enough hope to make you happy? ' \ 'Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.' words_list = re.split(r'\W+', s) print((Counter(words_list))) print(Counter(words_list).most_common(3))
运行结果
[8, 14, 12, 14, 15, 9, 10, 8, 19, 19, 2, 6, 4, 1, 6, 5, 19, 1, 5, 4, 15, 3, 7, 19, 17, 9, 10, 5, 9, 10]
{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0}
{1: 2, 2: 1, 3: 1, 4: 2, 5: 3, 6: 2, 7: 1, 8: 2, 9: 3, 10: 3, 11: 0, 12: 1, 13: 0, 14: 2, 15: 2, 16: 0, 17: 1, 18: 0, 19: 4, 20: 0}
--------------------------------------------------
Counter({19: 4, 5: 3, 9: 3, 10: 3, 1: 2, 4: 2, 6: 2, 8: 2, 14: 2, 15: 2, 2: 1, 3: 1, 7: 1, 12: 1, 17: 1, 11: 0, 13: 0, 16: 0, 18: 0, 20: 0})
[(19, 4), (5, 3), (9, 3)]
Counter({'you': 7, 'enough': 4, 'to': 4, 'make': 3, 'it': 2, 'hurts': 2, 'May': 1, 'have': 1, 'happiness': 1, 'sweet': 1, 'trials': 1, 'strong': 1, 'sorrow': 1, 'keep': 1, 'human': 1, 'hope': 1, 'happy': 1, 'Always': 1, 'put': 1, 'yourself': 1, 'in': 1, 'others': 1, 'shoes': 1, 'If': 1, 'feel': 1, 'that': 1, 'probably': 1, 'the': 1, 'other': 1, 'person': 1, 'too': 1, '': 1})
[('you', 7), ('enough', 4), ('to', 4)]