Oct-18-2018, 09:16 AM
There is also heapq for finding nlargest and nsmallest values.
From Python Cookbook, 3rd Edition by David Beazley; Brian K. Jones, O'Reilly Media 2013:
Borrowing nilamo's lambda it can be expressed:
From Python Cookbook, 3rd Edition by David Beazley; Brian K. Jones, O'Reilly Media 2013:
Quote:The nlargest() and nsmallest() functions are most appropriate if you are trying to find a relatively small number of items. If you are simply trying to find the single smallest or largest item (N=1), it is faster to use min() and max(). Similarly, if N is about the same size as the collection itself, it is usually faster to sort it first and take a slice (i.e., use sorted(items)[:N] or sorted(items)[-N:]). It should be noted that the actual implementation of nlargest() and nsmallest() is adaptive in how it operates and will carry out some of these optimizations on your behalf (e.g., using sorting if N is close to the same size as the input).
Borrowing nilamo's lambda it can be expressed:
>>> import heapq >>> lst = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] >>> heapq.nlargest(2, enumerate(lst), key=lambda x: x[1]) [(8, 42), (9, 37)]Or:
>>> heapq.nlargest(2, [(v, i) for i, v in enumerate(lst)]) >>> [(42, 8), (37, 9)]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.