python中找到最大或最小的N个元素的实现代码


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于python中找到最大或最小的N个元素的实现代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

1、需求

我们想在某个集合中找出最大或最小的N个元素

2、解决方案

heapq模块中有两个函数:nlargest()和nsmallest()

代码:

1

2

3

4

import heapq

nums=[1,444,66,77,34,67,2,6,8,2,4,9,556]

print(heapq.nlargest(3,nums))

print(heapq.nsmallest(3,nums))

结果:

1

2

[556, 444, 77]

[1, 2, 2]

这个两个函数都可以接受一个参数key,从而允许他们可以工作在更加复杂的数据结构上:

代码:

1

2

3

4

5

6

7

8

9

10

11

12

import heapq

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},

]

cheap=heapq.nsmallest(3,portfolio,key=lambda s:s['price'])

expensive=heapq.nlargest(3,portfolio,key=lambda s:s['price'])

print(cheap)

print(expensive)

结果:

1

2

[{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}]

[{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}]

如果只是简单的查找最小或者最大的元素(N=1),那么使用min()和max()会更快。

以上就是python中找到最大或最小的N个元素的实现代码的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python中is和==号的区别

Python作业:直方图、均衡化、高斯滤波

Python中all()函数和any()函数的便捷用法

Python如何做excel自动化

Python中dataframe按照行遍历的方法_Python

Python2和3哪个更常用

Python用pip安装numpy

win8怎么安装Python

Python中集合中的元素是否可以重复

Python怎么让输出在一行

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...