欢迎光临我要源码 ,本站所有资源仅供学习与参考,禁止用于商业用途或从事违法行为!

python教程

nlargest()和nsmallest()函数查找最大或最小元素方法

python教程 51源码 2022-11-07 人阅读

Python怎么从一个集合中获得最大或者最小的元素了?最简单的方法就是对集合进行排序操作,排序的算法则有冒泡、选择、插入等。Python标准模块heapq中提供了nlargest()和nsmallest()两个函数解决该问题。

nlargest()和nsmallest()用法 

nlargest()和nsmallest()两个函数都接受一个关键字参数,用于更复杂的数据结构中。示例代码如下: 

import heapq 
from random import randint  
nums = [randint(1, 100) for _ in range(5)] 
# 随机数列表,结果为:[89, 94, 26, 48, 3] 
print(nums) # 结果为:[94, 89, 48]
 print(heapq.nlargest(3, nums)) 
# 结果为:[3, 26, 48] 
print(heapq.nsmallest(3, nums))

当要查找的元素个数相对比较小时,函数nlargest()和nsmallest()是比较合适的。

如果仅仅是想查找唯一的最小值或者最大值,那么使用max()和min()函数会更快一些。

标签 python函数