finding maximum value in python list of tuples [duplicate]

寵の児 提交于 2019-12-11 02:35:46

问题


I have a list of tuples (list):

('2015-06-19', 3453455, 5, 'Scheduled')
('2015-05-19', 6786788, 6, 'Overdue')
('2015-04-19', 2342344, 2, 'Not Received')
('2015-03-19', 9438549, 0, 'Not Received')
('2015-02-19', 6348759, 7, 'Not Received')

When I run this, I get this:

>>> print(max(list))
('2015-06-19', 3453455, 5, 'Scheduled')

Obviously, max(list) determined the max based on the first value in the list of tuples. I'm just wondering if this is the default behavior of max(list) in regards to a list of tuples; to check only the first item in the tuple?

And, what if I wanted to return the tuple with the maximum based on the second item/column. How would I do that?


回答1:


You can specify which field to use for comparison using lambdas

max(list,key=lambda x:x[1])

or alternatively, using itemgetter

from operator import itemgetter
max(list,key=itemgetter(1))


来源:https://stackoverflow.com/questions/30534377/finding-maximum-value-in-python-list-of-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!