查找最大或最小的 N 個元素

查找最大或最小的 N 個元素

怎樣從一個集合中獲得最大或者最小的 N 個元素列表?對於熟悉python的人來說,解決這個問題的方法十分簡單。
即使用heapq模塊。
heapq 模塊有兩個函數:nlargest() 和 nsmallest() 可以完美解決這個問題。

import heapq
import random

num = [random.randint(10, 1000) for i in range(10)]
print(num)
print(heapq.nlargest(3, num))
print(heapq.nsmallest(3, num))

測試輸出如下:

[726, 180, 357, 781, 209, 177, 926, 666, 86, 254]
[926, 781, 726]
[86, 177, 180]

這樣就可以得出一個列表中最大和最小的三個數。
當然他的應用不止於此,還可以與lambda函數結合使用,用於處理更復雜的數據結構。

import heapq
# 用於美化輸出字典
import pprint


test_dict = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'APPLE', 'shares': 50, 'price': 543.22},
    {'name': 'DELL', 'shares': 200, 'price': 21.09},
    {'name': "GOOGLE', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, test_dict , key=lambda s: s['price'])
expensive = heapq.nlargest(3, test_dict , key=lambda s: s["price"])

pprint.pprint(cheap)
pprint.pprint(expensive)

得到輸出結果如下:

[{'name': 'YHOO', 'price': 16.35, 'shares': 45},
 {'name': 'DELL', 'price': 21.09, 'shares': 200},
 {'name': 'GOOGLE', 'price': 31.75, 'shares': 35}]
[{'name': 'APPLE', 'price': 543.22, 'shares': 50},
 {'name': 'ACME', 'price': 115.65, 'shares': 75},
 {'name': 'IBM', 'price': 91.1, 'shares': 100}]

這樣就得到了列表中價格最小和價格最大的三個字典元素。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章