Python教程-Python找到最大的N(前N个)或最小的N个项目

教程分享 > Python教程 (3377) 2024-07-19 16:52:09

Python示例使用heapq库中的nlargest()nsmallest()函数从元素集合中找到最大(或最小)的N个元素

 

1.使用heapq模块的nlargest()和nsmallest()

Python heapq模块可用于从集合中查找N个最大或最小的项目。它具有两个功能来帮助–

  1. nlargest()
  2. nsmallest()

1.1。在简单的可迭代对象中查找项目

$title(example1.py)
>>> import heapq
 
>>> 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。查找复杂的可迭代项

$title(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=lambda s: s['price'])
>> cheap
>>> [
        {'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=lambda s: 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://www.leftso.com/article/727.html

相关文章
前言本教程学习在Python中使用CSV文件
Python简介​Python是一种流行的编程语言,由Guido van Rossum创建,并于1991年发布
一.前言俗话说,工欲善其事必先利其器,本教程主要讲解如何在sublime编辑器中安装python软件包,以实现自动完成等功能,并在sublime编辑器本身中运行build
前言在Python(或任何其他编程语言)中,注释用于解释源代码
Python –数据类型数据类型定义变量的类型
了解python中的变量,声明局部变量和全局变量
Python httplib2 简介学习使用Python httplib2模块
​Python关键字是python编程语言的保留字,这些关键字不能用于其他目的
Python string.startswith()方法用于检查特定文本模式(例如URL方案等)的字符串以什么开头
Python示例,用于查找2个或更多词典之间的公共项,即字典相交项
Python string.endswith()用于检查特定文本模式(例如域名扩展等)的字符串结尾
使用字符串中的分隔符将字符串拆分为字段的 Python示例
1. Python整数类型值​​​​​​​​在Python中,一个int或整数是:不含小数的整数正,负或零无限长度可能包含下划线以提高可读性x = 10 y = 123456789876543...
Python示例将N元素元组或序列解压缩为N个变量的集合
​​​​​​​​Python 语言中的String在Python中,String代指以下特点:代表Unicode字符的字节数组用单引号或双引号引起来无限长度Python 中 String 字符串...