heapq nlargest Picks The Top K In One Pass
heapq.nlargest and nsmallest return the top or bottom k items without sorting everything, the stdlib shortcut when k is small next to the collection length.
Code
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])Output
Captured from a sandboxed run of this snippet in the build pipeline.
top 2: [('grace', 99), ('alan', 95)]
bottom 2: [('linus', 78), ('kay', 84)]
hottest: [25.1, 24.3]
coldest: [18.9, 19.8]
equals sorted slice: TrueWhat the code does
The file’s state is a handful of top-level bindings: scores, top2, temps.
Points of care
- External dependency:
heapq— install it before running the snippet.
Applying it
The demo output is labeled (top 2:, bottom 2:, hottest:), so every printed line maps back to its originating operation.
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `heapq`. Its state lives in module-level bindings: `scores`, `top2`, `temps`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.