# python的headq模块
# 从列表中找出最大或者最小的N个元素
import heapq
import heapq
list1 = [34, 25, 12, 99, 87, 63, 58, 78, 88, 92]
list2 = [
{'name': 'huawei', 'shares': 100, 'price': 91.1},
{'name': 'xiaomi', 'shares': 50, 'price': 543.22},
{'name': 'apple', 'shares': 200, 'price': 21.09},
{'name': 'meizu', 'shares': 35, 'price': 31.75},
{'name': 'oppo', 'shares': 45, 'price': 16.35},
{'name': 'vivo', 'shares': 75, 'price': 115.65}
]
print(heapq.nlargest(3, list1))
print(heapq.nsmallest(3, list1))
print(heapq.nsmallest(2, list2, key=lambda x: x['price']))
print(heapq.nlargest(2, list2, key=lambda x: x['price']))
以上内容属于Python进阶比较经典的用法,欢迎大家补充。如果你觉得不错,欢迎关注我置顶的公众号:shenbianshi88
你的支持,是我进步的最大动力,编程人生,快乐分享,欢迎你我,共同进步。