2

I need to find k-smallest values of tuples according to their second indexes in python, for example i have a list of tuples that contain distance of some points from the fix point, like : [('p1',12.5),('p2',3),('p4',1),('p5',16),('p6',15),...](from fixed point p0) and i want to find k-smallest values according to distances.

I mean something like this code, which is explianed here : Find the k smallest values of a numpy array

I would appreciate for your solutions

Psidom
  • 209,562
  • 33
  • 339
  • 356
Captain
  • 193
  • 1
  • 10

1 Answers1

4

You can use heapq.nsmallest, and specify the second element in the tuple as the comparison key:

from heapq import nsmallest 

lst = [('p1',12.5),('p2',3),('p4',1),('p5',16),('p6',15)]
nsmallest(3, lst, key=lambda x: x[1])
# [('p4', 1), ('p2', 3), ('p1', 12.5)]
Psidom
  • 209,562
  • 33
  • 339
  • 356