Reputation: 565
I'm aware of how to get the n highest values in a list but I want a quick function that gets the highest y values of a coordinate pair.
I know the following gives the n highest values in a list
[a[i] for i in np.argsort(a)[-n:]]
But what I really want is to feed it coordinates of the form
[[1,2], [3,4], [6,2], [6,11], [1,5]]
and get n coordinates with the highest y values from it, i.e. for n = 2
[[6,11], [1,5]]
But I can't quite get past the last step. Not having to use external libraries other than numpy would be a bonus. I tried changing the axis of argsort(list, axis=0) but that didn't work. Thanks
Upvotes: 3
Views: 760
Reputation: 221614
Here's one NumPy based approach with np.argsort
-
n = 2 # Number of entries to keep
arr = np.asarray(input_list) # Convert to array for further processing
out = arr[arr[:,1].argsort()[-n:]].tolist()
Another NumPy based one and should be faster with np.argpartition
-
out = arr[(-arr[:,1]).argpartition(n,axis=0)[:n]].tolist()
Upvotes: 1
Reputation: 11635
As an alternative, terser, answer you could use nlargest
from heapq
nlargest(n, your2DList, key=lambda x: x[-1])
Upvotes: 4
Reputation: 140216
just sort the list using 2nd coord as key, and print the 2 last items:
z = [[1,2], [3,4], [6,2], [6,11], [1,5]]
print(sorted(z,key=lambda x:x[1])[-2:])
result:
[[1, 5], [6, 11]]
Upvotes: 2
Reputation: 5304
A sorted
function takes named argument key
which is used to compute a compare key for each value.
>>> sorted([[1,2], [3,4], [6,2], [6,11], [1,5]], key=lambda pair: pair[1])[-n:]
[[1, 5], [6, 11]]
Upvotes: 3