pythonlisttime-seriesreorderlist

How to combine two lists of lists element-wise?


In Python, I would like to combine lists of lists in a very specific way, but I could not find it yet. Any ideas are welcome!

With the following input:

firstList = [[[1], [2], [3]], [[4], [5], [6]]]
secondList = [[[11], [12], [13]], [[14], [15], [16]]]

I would like to get the following output:

[[[1, 11], [2, 12], [3, 13]], [[4, 14], [5, 15], [6, 16]]]

I tried:

[list(a) for a in zip(firstList, secondList)]

but this returns:

[[[[1], [2], [3]], [[11], [12], [13]]], [[[4], [5], [6]], [[14], [15], [16]]]]

I need the desired output to get the correct format to be able to use the function TimeSeriesKMeans() from the module tslearn with time series in 2 dimensions


Solution

  • Since you are having nested lists, you need to double zip through your list. You can do:

    [[a + b for a, b in zip(x, y)] for x, y in zip(firstList, secondList)]
    

    Code:

    firstList = [[[1], [2], [3]], [[4], [5], [6]]]
    secondList = [[[11], [12], [13]], [[14], [15], [16]]]
    
    result = [[a + b for a, b in zip(x, y)] for x, y in zip(firstList, secondList)]
    # [[[1, 11], [2, 12], [3, 13]], [[4, 14], [5, 15], [6, 16]]]