怎样从一个集合中获得最大或者最小的 N 个元素列表? Copyright 2017, 熊能. Revision 402557a5.

解决方案:

heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题

import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

猜你喜欢

转载自www.cnblogs.com/ltk-python/p/9234056.html