Python Glossary Русский

all Python 3heapqfunction

heapq.nlargest()

selection

Return a list of the n largest items in descending order; accepts key= like sorted(). For n close to len(iterable) a plain sorted() is cheaper.

Syntax

heapq.nlargest(n, iterable, key=None)

It walks the iterable once and holds only n items in memory, so a generator or a huge file is fine; the cost is on the order of m·log n for a stream of m items. Both ends of the range are better served by something else: n=1 is just max(), and n close to the size of the data is plain sorted(). Items that tie on key keep their original order, matching sorted().

Examples

import heapq
data = [3, 1, 4, 1, 5, 9, 2, 6]
heapq.nlargest(3, data) # → [9, 6, 5]
records = [{'v': 5}, {'v': 1}, {'v': 9}]
heapq.nlargest(2, records, key=lambda x: x['v'])
# → [{'v': 9}, {'v': 5}]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy