Reputation: 3345
I have a list looks like this:
[(0, '2015-10-08'), (1, '2020-11-17'), (2, '2006-09-14'),....]
I want to return the one with the latest date, how can I achieve this?
I tried:
a= [(0, '2015-10-08'), (1, '2020-11-17'), (2, '2006-09-14')]
print(max(a))
but this returns (2, '2006-09-14')
, I'm confused, why is this? Thanks.
Upvotes: 1
Views: 1051
Reputation: 199
Doing max(a)
is looking at the zeroth element and finding the max, which is 2. You want to only look at the elements with the dates in so you need a[[i[1] for i in a].index(max([i[1] for i in a]))]
.
That might look a bit confusing because it's all on one line.
Essentially what it does is this:
You want to make a list b
of only the date elements. b = [i[1] for i in a]
.
Then find the index of the max of that list. max_index = b.index(max([i[1] for i in a]))
, this returns '1', so we know it's the element at position 1.
Finally, you need to get a[1]
, the element of a at position 1.
So all together it's a[[i[1] for i in a].index(max([i[1] for i in a]))]
. 🦄
Upvotes: 0
Reputation: 1586
In your code as you have used max
function it is comparing the first element of each tuple and giving the result.
I hope the below code sample would satisfy your use case -
a= [(0, '2015-10-08'), (1, '2020-11-17'), (2, '2006-09-14')]
n=len(a)
max_date=a[0][1]
for i in range(1,n):
date=a[i][1]
if(max_date < date):
max_date=date
print(max_date)
Upvotes: 0
Reputation: 160
Try this:
print(max(a, key=lambda x: datetime.datetime.strptime(x[1], '%Y-%m-%d')))
You can use the max() function with key parameter to get max element according to a function.
Upvotes: 3
Reputation: 91
When you use max(a)
it returns the maximum first element in your tuple which is 2. Hence, max(a) = (2, '2006-09-14')
I suggest you this code :
import numpy as np
list_dates=[]
for i in np.arange(len(a)):
list_dates.append(a[i][1])
max(list_dates)
It returns
'2020-11-17'
Upvotes: 0
Reputation: 1728
When comparing tuples, the default behavior is to compare their first element, and then the second element if there is a tie, and so on. So when you call max([(0, '2015-10-08'), (1, '2020-11-17'), (2, '2006-09-14')])
, you get (2, '2006-09-14')
because it has the largest first element.
You need to pass a custom function to the key
argument of the builtin max
function in order to make it compare on the dates:
>>> from datetime import datetime
>>> arr = [(0, '2015-10-08'), (1, '2020-11-17'), (2, '2006-09-14')]
>>> max(arr, key=lambda item: datetime.strptime(item[1], "%Y-%m-%d"))
(1, '2020-11-17')
Upvotes: 0
Reputation: 607
Default max function works on first element of tuple. You can set this to second element by max(a, key=lambda x: x[1])
Upvotes: 3