heapq模块是用来求前n个最大/最小值的。
import heapq
# 用内置函数sorted()求最大/最小
lst = [38, 45, 19, 9, -12, 3, 97, 79, 199, 20, -49]
l_largest = sorted(lst, reverse=True)[:3]
l_smallest = sorted(lst)[:3]
print(l_largest)
print(l_smallest)
# 用模块函数nlargest()/nsmallest()求最大/最小
h_largest = heapq.nlargest(3, lst)
h_smallest = heapq.nsmallest(3, lst)
print(h_largest)
print(h_smallest)
# 用heapq.merge(*heap)进行多列表合并,并进行堆调整,返回合并后列表的迭代器
l1 = [1, 3, 5, 7, 9]
l2 = [2, 4, 6, 8]
l = heapq.merge(l1, l2)
print(list(l))
# 以下表示一些书的价格,找出单价最高和最低的两本书
books_price = [{'book':'python', 'price':'69.99'},
{'book':'jave', 'price':'59.99'},
{'book':'rust', 'price':'79.99'},
{'book':'javescript', 'price':'49.99'},
{'book':'c++', 'price':'89.99'},
{'book':'ruby', 'price':'39.99'},
{'book':'hadoop', 'price':'99.99'},
{'book':'html5', 'price':'29.99'}]
top1 = heapq.nlargest(1, books_price, key=lambda s: s['price'])
low1 = heapq.nsmallest(1, books_price, key=lambda s: s['price'])
print(top1)
print(low1)
输出结果:
[199, 97, 79]
[-49, -12, 3]
[199, 97, 79]
[-49, -12, 3]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[{'book': 'hadoop', 'price': '99.99'}]
[{'book': 'html5', 'price': '29.99'}]