return [elem for (elem, order) in result]
# General case, slowest method
result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
_heapreplace = _heapreplace_max
_heapreplace(result, (k, order, elem))
top, _order, _elem = result[0]
return [elem for (k, order, elem) in result]
def nlargest(n, iterable, key=None):
"""Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
# Short-cut for n==1 is to use max()
result = max(it, default=sentinel, key=key)
return [] if result is sentinel else [result]
# When n>=size, it's faster to use sorted()
except (TypeError, AttributeError):
return sorted(iterable, key=key, reverse=True)[:n]
# When key is none, use simpler decoration
result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]
_heapreplace = heapreplace
_heapreplace(result, (elem, order))
result.sort(reverse=True)
return [elem for (elem, order) in result]
# General case, slowest method
result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
_heapreplace = heapreplace
_heapreplace(result, (k, order, elem))
top, _order, _elem = result[0]
result.sort(reverse=True)
return [elem for (k, order, elem) in result]
# If available, use C implementation
from _heapq import _heapreplace_max
from _heapq import _heapify_max
from _heapq import _heappop_max
if __name__ == "__main__":
import doctest # pragma: no cover
print(doctest.testmod()) # pragma: no cover