![](/img/trans.png)
[英]Elegant way to find mutually exclusive tuples in the list based on the element present in each tuple
[英]Elegant way to extract a tuple from list of tuples with minimum value of element
我有元组列表,我希望元组在索引1
处具有最小值。 例如,如果我的列表如下:
a =[('a', 2), ('ee', 3), ('mm', 4), ('x', 1)]
我希望返回的元组为('x', 1)
。
目前我使用sorted
函数得到这样的结果:
min=sorted(a, key=lambda t: t[1])[0]
有更好的方法吗? 也许有min
功能?
您可以将min()
函数与key
参数一起使用,以便在列表中找到具有最小值的元组。 无需对列表进行排序。 因此,你的min
呼叫应该是:
>>> min(a, key=lambda t: t[1])
('x', 1)
甚至更好地使用operator.itemgetter()
而不是lambda表达式 ; 作为itemgetter比较快。 在这种情况下,对min
函数的调用应该是:
>>> from operator import itemgetter
>>> min(a, key=itemgetter(1))
('x', 1)
注意: min()
是Python中的内置函数。 您不应该将它用作变量名。
这也有效:
min([x[::-1] for x in a])[::-1]
# ('x', 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.