How do I get the largest or smallest list of n elements from a collection?
The HEAPQ module has two functions: nlargest()
and nsmallest()
can solve this problem perfectly.
Import Heapqin [+]: nums = [2, 5, 3, 4]in [in]: Heapq.nlargest (2, nums) out[[5]: [, 4]in [42] ]: Heapq.nsmallest (2, nums) out[42]: [2, 3]
Two functions can accept a keyword parameter for more complex data structures:
Compare by Price value
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=Lambdas:s[' Price']) Expensive= Heapq.nlargest (3, Portfolio, key=Lambdas:s[' Price'])
Use HEAPQ in Python to see a list of the largest and smallest n elements