当前位置: 首页 > 后端技术 > Python

(Python基础教程第11期)Python求最大N(topN)或最小N项

时间:2023-03-26 17:17:37 Python

Python基础教程在SublimeEditor中配置Python环境在Python代码中添加注释Python中变量的使用Python中的关键字Python字符串操作Python之Python列表操作Python之元组操作Pythonmax()和min()——求列表或数组中的最大值和最小值Python求最大N(topN)或最小N项Python读写CSV文件在Python中使用httplib2–HTTPGET和POST示例Python拆箱元组作为变量或参数Python拆箱元组–太多值无法拆包Pythonmultidict示例–将单个键映射到字典Python中的多个值OrderedDict–有序字典Python字典交集——比较两个字典Python优先级队列示例元素。1.使用heapq模块的nlargest()和nsmallest()Pythonheapq模块可用于从集合中查找N个最大或最小的项目。它有两个函数可以提供帮助——nlargest()nsmallest()1.1。在简单的可迭代example1.py中查找项目>>>importheapq>>>nums=[1,8,2,23,7,-4,18,23,42,37,2]print(heapq.nlargest(3,nums))>>>[42,37,23]print(heapq.nsmallest(3,nums))>>>[-4,1,2]1.2。查找复杂的可迭代对象example2.py>>>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}]>>>cheap=heapq.nsmallest(3,portfolio,key=lambdas:s['price'])>>便宜>>>[{'price':16.35,'name':'YHOO','shares':45},{'price':21.09,'name':'FB','shares':200},{'price':31.75,'name':'HPQ','shares':35}]>>>expensive=heapq.nlargest(3,portfolio,key=lambdas:s['price'])>>>expensive>>>[{'price':543.22,'name':'AAPL','shares':50},{'price':115.65,'name':'ACME','shares':75},{'price':91.1,'name':'IBM','shares':100}]如果你只想找到一个分钟或最大项(N=1),然后[使用min()和max()函数]更快。快乐学习!作者:分布式编程来源:https://zthinker.com/如果您喜欢本文,请长按二维码关注分布式编程。