I have a list of tuples. Each tuple holds two things:
1. A distance
2. A topic name
Now I want to find out thek
smallest distances from this list. The list size is very big and k
is quite small (k <= 5
).
I think numpy.argpartition
would have an edge instead of just sorting the entire list. This answer describes how to perform argparition
on an 1-D array.
For example, let's say we have the following:
L = [(0.5, 'Anime'), (0.3, 'Arduino'), (0.7, 'Chess'), (0.1, 'Coffee'), (0.9, 'Space')]
A = np.asarray(L)
Now if k = 3
, then after performing argparition
, we should have the following indices
array:
idx = [1 3 0 2 4]
And so print(A[idx[:k]])
would give:
[(0.1, 'Coffee'), (0.3, 'Arduino'), (0.5, 'Anime')]
The above was a simulation that I want to achieve. But given that I have a tuple, how can I perform argparition
based on the first element of each tuple (i.e. the distance)?