找到最大或最小的N个元素

2020-12-23  本文已影响0人  Little茂茂
import heapq


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

portfolio = [
    {'name': 'IBM', 'share': 100, 'price': 91.1},
    {'name': 'APPL', 'share': 50, 'price': 543.22},
    {'name': 'FB', 'share': 200, 'price': 21.09},
    {'name': 'HPQ', 'share': 35, 'price': 31.75},
    {'name': 'YHOO', 'share': 45, 'price': 16.35},
    {'name': 'ACME', 'share': 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)

# 寻找最大或最小的元素数量远小于元素总数
heap = list(nums)
heapq.heapify(heap)
print(heapq)
for _ in range(4):
    print(heapq.heappop(heap))

# 寻找最大或最小元素
print(max(nums))
print(min(nums))

# 寻找最大或最小元素数量和元素总数差不多
print(sorted(nums)[:4])
print(sorted(nums)[-4:])


上一篇下一篇

猜你喜欢

热点阅读