实现说明
各个操作都建立在顶层绑定之上:scores、top2、temps。
使用要点
- 每一步打印都带着自己的标签:
top 2:、bottom 2:、hottest:。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 全部导入都来自标准库:heapq。 文件用顶层绑定保存自己的状态:scores、top2、temps。
代码示例
import heapq
scores = [("ada", 91), ("linus", 78), ("grace", 99), ("kay", 84), ("alan", 95)]
# nlargest(k, iterable, key):等价于 sorted(..., reverse=True)[:k]
top2 = heapq.nlargest(2, scores, key=lambda item: item[1])
print("top 2:", top2)
# nsmallest 升序返回垫底者
print("bottom 2:", heapq.nsmallest(2, scores, key=lambda item: item[1]))
# 普通数值列表不需要 key
temps = [21.5, 19.8, 25.1, 22.0, 18.9, 24.3]
print("hottest:", heapq.nlargest(2, temps))
print("coldest:", heapq.nsmallest(2, temps))
# k 接近总长度时 sorted 更快;top-k 占比小才是 nlargest 的主场
print("equals sorted slice:", heapq.nlargest(3, temps) == sorted(temps, reverse=True)[:3])