1. Python Basics
  2. Configure the Python environment in the SublimeEditor
  3. Add comments to Python code
  4. The use of variables in Python
  5. Data types in Python
  6. Keywords in Python
  7. Python string manipulation
  8. The list operation in Python
  9. The Tuple operation in Python
  10. Pythonmax () and min () – Look for maximum and minimum values in a list or array
  11. Python finds the largest N (first N) or smallest N items
  12. Python reads and writes CSV files
  13. Use httplib2 — HTTPGET and POST examples in Python
  14. Python unboxes tuples as variables or arguments
  15. Python unboxed Tuple – Too many values to unpack
  16. Pythonmultidict example – maps a single key to multiple values in a dictionary
  17. PythonOrderedDict – Ordered dictionaries
  18. Python dictionary intersection – compares two dictionaries
  19. Python priority queue example

The Python example uses the nlargest () and nsmallest () functions in the Heapq library to find the largest (or smallest) N elements in a collection of elements.

1. Use heapq module nlargest () and Nsmallest ()

The Python HeAPq module can be used to find N largest or smallest items from a collection. It has two features to help —

  1. nlargest()
  2. nsmallest()

1.1. Find items in a simple iterable

example1.py

>>> import heapq

>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

print(heapq.nlargest(3, nums)) 

>>> [42, 37, 23]

print(heapq.nsmallest(3, nums))

>>> [-4, 1, 2]Copy the code

1.2. Find complex iterable items

example2.py

= > > > portfolio [{' name ':' IBM ', 'shares' : 100,' price: 91.1}, {' name ':' both ', 'shares' : 50,' price: 543.22}, {' name ':' FB ', 'shares' : 200,' price: 21.09}, {' name ':' point ', 'shares' : 35,' price: 31.75}, {" name ": 'way', 'shares' : 45,' price: 16.35}, {' name ':' ACME ', 'shares' : 75,' price: Nunit (3, portfolio, key=lambda s: s['price']) >>> > [{'price': 16.35, 'name': 'way', 'shares' : 45}, {' price: 21.09,' name ':' FB ', 'shares' : 200}, {' price: 31.75,' name ':' point ', 'shares' : 35} ] >>> expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) >>> expensive >>> [ {'price': 543.22, the 'name' : 'both', 'shares' : 50}, {' price: 115.65,' name ':' ACME ', 'shares' : 75}, {' price: 91.1,' name ': 'IBM', 'shares': 100} ]Copy the code

It is faster [using the min() and Max () functions] if you just want to find a single smallest or largest item (N=1).

Happy study!

The author:Distributed programmingReference:zthinker.com/If you like this article, please long press the QR code, followDistributed programming .