[英]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.