I am doing some works for studying, and stuck in some problems!
I have this schedule lists
lists = [['Lunch', '2021-04-05 12:00', '2021-04-05 13:00'], ['Dinner', '2021-04-05 13:00', '2021-04-05 14:00'], ['Lunch', '2021-04-04 13:00', '2021-04-04 14:00']]
And, I would like to sort this list by start date which is lists[1]
What I tried to do is below
lists = [['Lunch', '2021-04-05 12:00', '2021-04-05 13:00'], ['Dinner', '2021-04-05 13:00', '2021-04-05 14:00'], ['감자', '2021-04-04 13:00', '2021-04-04 14:00']] sorted_lists = [] for i in lists: i[1] = i[1].replace('-', '').replace(' ', '').replace(':', '') i[2] = i[1].replace('-', '').replace(' ', '').replace(':', '') sorted_lists.append(i) sorted(sorted_lists, key=lambda date: date[1]) print(sorted_lists)
Note, I don’t want to use any module such as date, time
But, it switch the location of each items.
Is there any best way to sort by start date?
Thank you.
If my explanation is bad, please let me know..!
Thank you guys for reading
Advertisement
Answer
If your dates are as you show (i.e., their lexical order is consistent with the time order), then why not simply:
sorted(lists, key=lambda e: e[1])
For the data you gave, that gives:
[['Lunch', '2021-04-04 13:00', '2021-04-04 14:00'], ['Lunch', '2021-04-05 12:00', '2021-04-05 13:00'], ['Dinner', '2021-04-05 13:00', '2021-04-05 14:00']]
Clarification: I always try to avoid side-effects in my answers. That means that the code I provide usually creates new values and doesn’t affect existing variables, unless duly noted. I consider these side-effects to be potentially dangerous, unless very clearly documented. Imagine a function that you call sneakily modifying your lists or your DataFrame in-place…
As such, the answer above should be assigned to a result variable of choice. I see you use sorted_lists
, so:
sorted_lists = sorted(lists, key=lambda e: e[1])