0

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?

human
  • 735
  • 2
  • 8
  • 17
  • 1
    possible duplicate of [Flattening a shallow list in Python](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – TigerhawkT3 Aug 20 '15 at 23:33
  • 2
    Can you reproduce your data? The code above should not produce any `int`s. – metatoaster Aug 20 '15 at 23:33
  • You can unzip a list of 3 2-tuples into two 3-tuples with a, b = zip(*list1) where a = (datetime1, datetime3, datetime5) and b = (datetime2, datetime4, datetime6). To combine them in one tuple just add them with +, convert to a list with list() and sort with sorted, i,e. list2 = sorted(list(a+b)). Another approach is list2 = [i for s in list(map(list, list1)) for i in s] –  Aug 20 '15 at 23:55
  • This is not a dupe, the OP's code would already flatten the list – Padraic Cunningham Aug 21 '15 at 00:07

2 Answers2

0

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
ThatGuyRussell
  • 1,361
  • 9
  • 18
0

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.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321