[英]Elegant way to extract a tuple from list of tuples with minimum value of element
I am having list of tuple from which I want the tuple with the minimum value at index 1
. 我有元组列表,我希望元组在索引
1
处具有最小值。 For example, if my list is like: 例如,如果我的列表如下:
a =[('a', 2), ('ee', 3), ('mm', 4), ('x', 1)]
I want the returned tuple to be ('x', 1)
. 我希望返回的元组为
('x', 1)
。
Currently I am using sorted
function to get this result like: 目前我使用
sorted
函数得到这样的结果:
min=sorted(a, key=lambda t: t[1])[0]
Is there better ways to do it? 有更好的方法吗? Maybe with
min
function? 也许有
min
功能?
You may use min()
function with key
parameter in order to find the tuple with minimum value in the list. 您可以将
min()
函数与key
参数一起使用,以便在列表中找到具有最小值的元组。 There is no need to sort the list. 无需对列表进行排序。 Hence, your
min
call should be like: 因此,你的
min
呼叫应该是:
>>> min(a, key=lambda t: t[1])
('x', 1)
Even better to use operator.itemgetter()
instead of lambda expression ; 甚至更好地使用
operator.itemgetter()
而不是lambda表达式 ; as itemgetter are comparatively faster. 作为itemgetter比较快。 In this case, the call to
min
function should be like: 在这种情况下,对
min
函数的调用应该是:
>>> from operator import itemgetter
>>> min(a, key=itemgetter(1))
('x', 1)
Note: min()
is a in-built function in Python. 注意:
min()
是Python中的内置函数。 You should not be using it as a variable name. 您不应该将它用作变量名。
This will also work: 这也有效:
min([x[::-1] for x in a])[::-1]
# ('x', 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.