python大学实用教程练习7.1.4(heapq模块)

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'}]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

juicy-hua

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值