Home  >  Article  >  Backend Development  >  Implementation code for finding the largest or smallest N elements in python

Implementation code for finding the largest or smallest N elements in python

不言
不言forward
2018-10-11 14:15:112402browse

This article brings you the implementation code for finding the largest or smallest N elements in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Requirements

We want to find the largest or smallest N elements in a certain set

2.Solution

There are two functions in the heapq module: nlargest() and nsmallest()

Code:

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))

Result:

[556, 444, 77]
[1, 2, 2]

These two Each function can accept a parameter key, allowing them to work on more complex data structures:

Code:

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)

Result:

[{'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}]

If it is just simple To find the smallest or largest element (N=1), it will be faster to use min() and max().


The above is the detailed content of Implementation code for finding the largest or smallest N elements in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete