[英]Finding k-smallest values of 2D tuples according to their second index
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. 我需要根据它们在python中的第二个索引找到k个最小的元组值,例如,我有一个元组列表,其中包含距固定点某些点的距离,例如: [('p1',12.5),('p2',3),('p4',1),('p5',16),('p6',15),...](from fixed point p0)
,我想根据到距离。
I mean something like this code, which is explianed here : Find the k smallest values of a numpy array 我的意思是这样的代码,在这里解释如下: 查找numpy数组的k个最小值
I would appreciate for your solutions 谢谢您的解决方案
You can use heapq.nsmallest
, and specify the second element in the tuple as the comparison key: 您可以使用heapq.nsmallest
,并将元组中的第二个元素指定为比较键:
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.