1

I have list of lists of lists and need to combine the inner lists accordingly.

For example:

1. mylist=[[[1]], [[2]]]

2.

mylist= [[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
         [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
         [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]]]

(in short-[[[1]*3]*4, [[2]*3]*4, [[3]*3]*4])

Expected output-

  1. [[[1, 2]]]
[[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
 [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
 [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
 [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

(in short-[[[1, 2, 3]]*3]*4)

This is what I have untill now-

def combine_channels(mylist):
    elements = [[] for _ in range(len(mylist[0]))]
    for l1 in mylist:
        for idx, l2 in enumerate(l1):
            elements[idx] += l2

    return [elements]

The problem is that the output is (for input example 2)-

[[[1, 1, 1, 2, 2, 2, 3, 3, 3],
 [1, 1, 1, 2, 2, 2, 3, 3, 3],
 [1, 1, 1, 2, 2, 2, 3, 3, 3], 
[1, 1, 1, 2, 2, 2, 3, 3, 3]]]

and not-

[[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
 [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
 [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
 [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]
yaeB
  • 49
  • 6

1 Answers1

1
mylist = [[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
         [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
         [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]]]

def combine_channels(mylist):
    def list_zip(_list):
        return list(zip(*_list))

    elements = []
    for l in list_zip(mylist):
        elements.append(list_zip(l))
    return elements

combine_channels(mylist)
MonkChen
  • 26
  • 1
  • It is almost perfect , it returnes tuaples insted of lists-[[(1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3)]] – yaeB Apr 20 '22 at 13:15
  • You may make them be lists like this `return [list(el) for el in zip(*_list)]`, or better: [take a look here](https://stackoverflow.com/a/41016636/13541354) – ALai Apr 20 '22 at 13:46