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

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

不言
Release: 2018-10-11 14:15:10
forward
2456 people have browsed it

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))
Copy after login

Result:

[556, 444, 77]
[1, 2, 2]
Copy after login

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)
Copy after login

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}]
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template