Reputation: 3760
I have a list that looks roughly like this:
mylist = [[2, 20200101], [2, 20200108], [2, 20200101], [1, 20200110], [1, 20200101]]
It is a list of lists, each of which has a value as the first element, and a date as the second. I want to choose the list which first has the highest value (2 in this case) then the most recent date, (20200108 - 8th Jan 2020, in this case)
I know you can pass a lambda function to the built in max()
function, like below, but I am not sure how to handle choosing the max of first the value, then the date?
max(mylist, key=lambda x: x[0])
Upvotes: 0
Views: 318
Reputation: 35502
In Python, lists compare lexicographically by default. This means that the first element is compared, then the next, and so on, which is exactly what you want. (As a side note, shorter lists will be less than longer lists) So, you can just max
without a key:
max(mylist)
Upvotes: 1
Reputation: 3856
The default max
works from the first index to the last in an iterable sorting.
mylist = [[2, 20200101], [2, 20200108], [2, 20200101], [1, 20200110], [1, 20200101]]
max(mylist)
OR
You can pass two keys!
mylist = [[2, 20200101], [2, 20200108], [2, 20200101], [1, 20200110], [1, 20200101]]
max(mylist, key=lambda x: (x[0], x[1]))
Upvotes: 0