标签:col common 标准库 方案 数据 ict random for sort
#1.sorted排序
from random import randint
data = [randint(0, 20) for _ in range(30)] #创建数据
d = dict.fromkeys(data, 0) #创建字典
for x in data:
d[x] += 1 #统计词频
#((v, k) for k, v in d.items()):生成器解析,所需空间少
sorted(((v, k) for k, v in d.items()), reverse=True)[:3] #根据词频排序并截取前3
#2.heapq(堆)
import heapq
#heapq.nlargest 取前n个最大;heapq.nsmallest 取前n个最小
heapq.nlargest(3, ((v, k) for k, v in d.items()))
执行结果:
[(5, 2), (3, 14), (3, 13)]
from collections import Counter
c = Counter(data) #统计词频
c.most_common(3)
执行结果:
[(2, 5), (13, 3), (14, 3)]
标签:col common 标准库 方案 数据 ict random for sort
原文地址:https://www.cnblogs.com/huowuyan/p/11869232.html