某随机序列[12, 4, 6, 45, 12, 78, .....]中,找出出现次数最多的三个元素
以及他们出现的次数
- 利用默认值字典,先以键值对形式存储每个元素及出现的次数,然后将键值反转存储为元组,利用排序输出后三位
>>> from random import randint
>>> from collections import defaultdict
>>> data = [randint(0, 10) for _ in range(0, 30)]
>>> d = defaultdict(int)
>>> for x in data:
... d[x] += 1
...
>>> d
defaultdict(<class 'int'>, {0: 5, 1: 1, 2: 3, 3: 6, 4: 5, 5: 1, 6: 3, 7: 1, 8: 2, 9: 1, 10: 2})
>>> new_d = sorted([(v, k) for k, v in d.items()])
>>> new_d[-3:]
[(5, 0), (5, 4), (6, 3)]
- 但是对于这个问题用Counter是最简单而且高效的解决办法
>>> from random import randint
>>> from collections import Counter
>>> data = [randint(0, 10) for _ in range(0, 30)]
>>> c = Counter(data)
>>> c.most_common(3)
[(7, 5), (0, 4), (1, 4)]