I have a list of tuples full od datetime objects like this:
list1 = [(datetime1, datetime2), (datetime3, datetime4), (datetime5, datetim6)]
I want to convert it to a list of datetime objects, but when i use this code:
list2 = [i[j] for i in list1 for j in range(len(i))]
The result i got is the list of ints, not datetimes.
I also need later to sort the list2 by time, and then compare the list2 with a list1.
Any ideas?
When you add a tuple to a list it adds the inner variables separately, just use:
list1 = [("datetime1", "datetime2"), ("datetime3", "datetime4"), ("datetime5", "datetim6")]
list2 = []
for datetime in list1:
list2 += datetime
If you are going to sort and flatten do it in one step:
from itertools import chain
srt_dates = sorted(chain.from_iterable(list1)
If you want to sort just by the time and not the date and time, you can use a lambda as the sort key:
from itertools import chain
from datetime import datetime
list1 = [(datetime(2015, 1, 2, 15, 0, 10), datetime(2015, 1, 2, 12, 0, 10)),
(datetime(2015, 1, 2, 14, 05, 10), datetime(2015, 1, 4, 11, 0, 10))]
srt_dates = sorted(chain.from_iterable(list1), key=lambda x: (x.hour, x.min, x.second))
print(srt_dates)
[datetime.datetime(2015, 1, 4, 11, 0, 10), datetime.datetime(2015, 1, 2, 12, 0, 10), datetime.datetime(2015, 1, 2, 14, 5, 10), datetime.datetime(2015, 1, 2, 15, 0, 10)]
The only way [i[j] for i in list1 for j in range(len(i))]
would give you a list of ints is if you have reassigned the name list1
to a list that that has iterables than contain ints.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.