Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding maximum value in python list of tuples [duplicate]

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?

like image 775
Jeff F Avatar asked Dec 06 '22 21:12

Jeff F


1 Answers

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))
like image 137
nomis Avatar answered Jan 28 '23 23:01

nomis