欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何从一个集合中找到n个最大或最小的元素?python

程序员文章站 2022-07-03 20:48:13
...
import heapq
# heapq模块建立堆数据结构
nums = [1, 8, 2, 3, 123, 43, -1, 0, 90]
# eapq.nlargest(num, list)
lnums = heapq.nlargest(3, nums)
snums = heapq.nsmallest(3, nums)
print(lnums) # [123, 90, 43]
print(snums) # [-1, 0, 1]
numspor = [
    {'name': 'evil woman', 'face': 'unpretty', 'weight': 98},
    {'name': 'A woman', 'face': 'urgly', 'weight': 200},
    {'name': 's woman', 'face': 'beautiful', 'weight': 90},
    {'name': 'new s woman', 'face': 'most beautifu', 'weight': 85}
]
lnunspor = heapq.nlargest(2,numspor, key=lambda x: x['weight'])
snumspor = heapq.nsmallest(2,numspor, key=lambda x: x['weight'])
print(lnunspor)
# [{'name': 'A woman', 'face': 'urgly', 'weight': 200}, {'name': 'evil woman', 'face': 'unpretty', 'weight': 98}]
print(snumspor)
# [{'name': 'new s woman', 'face': 'most beautifu', 'weight': 85}, {'name': 's woman', 'face': 'beautiful', 'weight': 90}]