Skip to content Skip to sidebar Skip to footer

Indices Of The N Smallest Elements Of A List

i am trying to find 3 lowest number from a list and using those indexes to find corresponding value from another list. this is an example of what i have tried a = [12, 83, 22, 30

Solution 1:

What you can do is sort the list a and return it's index values,

>>>a = [12, 83, 22, 30, 57, 32, 88, 46, 20, 26, 78, 65, 45, 56, 74]>>>n_min_values = 3>>>sorted(range(len(a)), key=lambda k: a[k])[:n_min_values] 
[0, 8, 2] # index values

and iterate through this index values list to get corresponding values from list b,

>>>b = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o']>>>for i insorted(range(len(a)), key=lambda k: a[k])[:n_min_values ]:
        print(b[i])
a
i
c

OR

Using list comprehesion,

>>> [b[i] for i insorted(range(len(a)), key=lambda k: a[k])[:n_min_values ]]
['a', 'i', 'c'] # your output

Solution 2:

Heaps are good at doing this sort of thing, especially if the order of the smallest items isn't important.

Here's a small example using heapq.nsmallest on a with its zipped indices.

from heapq import nsmallest
from operator import itemgetter

n = 3
idx, _ = zip(*nsmallest(n, enumerate(a), key=itemgetter(1)))
idx
# (0, 8, 2)

[b[i] for i in idx]  # your result# ['a', 'i', 'c']

Post a Comment for "Indices Of The N Smallest Elements Of A List"