Python中有一个模块heapq,模块中有两个函数:nlargest()和nsmallest(),具体用法如下:
nums = ['abc', 'def', 'g', 'h', 'j']
max_n = heapq.nlargest(3, nums)
min_n = heapq.nsmallest(2, nums)
print(max_n) # prints['j', 'h', 'g']
print(min_n) # prints['abc', 'def']
nums = [8, 1, 2, 3, 4, 7, 6, 5]
max_n = heapq.nlargest(3, nums)
min_n = heapq.nsmallest(3, nums)
print(max_n) # prints[8, 7, 6]
print(min_n) # prints[1, 2, 3]
nums = [
{'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}
]
max_n = heapq.nlargest(1, nums, key=lambda s: s['price'])
min_n = heapq.nsmallest(1, nums, key=lambda s: s['price'])
print(max_n) # [{'name': 'AAPL', 'shares': 50, 'price': 543.22}]
print(min_n) # [{'name': 'YHOO', 'shares': 45, 'price': 16.35}]
它可以使用lambda函数进行复杂的排序