🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 问题: 怎样从一个集合中获得最大或者最小的 N 个元素列表 ### 解决方案: heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题 ```python import heapq nums = [1, 8, 32, 4, -1, 4, 89, 34, 5, 77, 5, 53476, 898, 243, 689, 60] print(heapq.nlargest(3, nums)) # [53476, 898, 689] 取最大的三个值 print(heapq.nsmallest(3, nums)) # [-1, 1, 4] 取最小的三个值 portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) print(cheap) print(expensive) ``` 原文来自; > https://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p04_find_largest_or_smallest_n_items.html