from random import randint #找出出现次数最多的前3个 data = [randint(0,20) for _ in range(30)] print(data) d = dict.fromkeys(data,1) print(d) for x in data: d[x] += 1 dd = sorted([(v,k) for k,v in d.items()],reverse=True) print(dd) print(dd[:3]) #堆 import heapq aa = heapq.nlargest(3,((v,k) for k,v in d.items())) print(aa) from collections import Counter d=Counter(data) print(d.most_common(3))
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9541389.html