import heapq
portfolio = [
{'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}
]
# 方法一
small= heapq.nsmallest(3, portfolio, key=lambda x: x["price"])
big= heapq.nlargest(3, portfolio, key=lambda x: x["price"])
print(small)
print(big)
# 方法二
max_price = sorted(portfolio, key=lambda x: x["price"],reverse=True)[:3:]
min_price = sorted(portfolio, key=lambda x: x["price"],reverse=False)[:3:]
print(max_price)
print(min_price)
方法一
n:你要几个元素
iterable:可迭代对象,比如列表、元组等等
key:你要根据可迭代对象里面的年一个元素进行排序
heapq.nsmallest:从小到大排序
heapq.nlargest:从大到小排序
方法二
返回一个新列表,其中包含按升序排列的iterable中的所有项。
可以提供自定义键函数来自定义排序顺序,以及可以将反转标志设置为按降序请求结果。
reverse=True)[:3:]:降序取前三个,不写[:3:]代表全部
reverse=False)[:3:]:升序取前三个,不惜代表全部