undefinedfix
Sign in

How to convert 3D list into 2D list in Python?

LogIN edited in Fri, 12 Aug 2022

A = [[1,2], [1,3], [2,5]], [[2,4], [2,5], [2,6]], [[3,5], [3,6]]] wants to be transformed into b = [[1,2], [1,3], [2,5], [2,4], [2,5], [2,6], [3,5], [3,6]]]

3 Replies
kqico
commented on Sat, 13 Aug 2022

print reduce(lambda x, y: [x.extend(y), x][1], A, []) == B

altegn0
commented on Sat, 13 Aug 2022

Sum (a, []) and reduce (lambda x, Y: x + y, a) can achieve this function,

But I hope you can think about it a little bit before you ask questions. At worst, it can be realized by using a for loop

k0r3n
commented on Sat, 13 Aug 2022

If you are not sure about the array dimension of each element, you need to do a deep traversal. The following is the python 3 code:

def dfs(tree):
    for i in tree:
        if type(i) == list:
            yield from dfs(i)
        else:
            yield tree
            break


B = list(dfs(A))
lock This question has been locked and the reply function has been disabled.