Elegant way to extract a tuple from list of tuples with minimum value of element

旧巷老猫 提交于 2019-12-01 21:50:42
Moinuddin Quadri

You may use min() function with key parameter in order to find the tuple with minimum value in the list. There is no need to sort the list. Hence, your min call should be like:

>>> min(a, key=lambda t: t[1])
('x', 1)

Even better to use operator.itemgetter() instead of lambda expression; as itemgetter are comparatively faster. In this case, the call to min function should be like:

>>> from operator import itemgetter

>>> min(a, key=itemgetter(1))
('x', 1)

Note: min() is a in-built function in 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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!