在 python 中将 3d 列表展平为 2d

Flatten 3d list to 2d in python

所以我在 python 中有一个列表列表,它是这样的:

[[[0, 1, 0, 1, 0]]
[[1, 1, 1, 1, 1]]
[[1, 0, 0, 1, 1]]
[[0, 1, 0, 0, 0]]]

我想展平这个列表并以这样的结尾:

[[0, 1, 0, 1, 0]
[1, 1, 1, 1, 1]
[1, 0, 0, 1, 1]
[0, 1, 0, 0, 0]]

在 python 中是否有直接的方法来做到这一点?

a = [[[0, 1, 0, 1, 0]], 
[[1, 1, 1, 1, 1]], 
[[1, 0, 0, 1, 1]], 
[[0, 1, 0, 0, 0]]]    

[i[0] for i in a]     

输出

[[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [1, 0, 0, 1, 1], [0, 1, 0, 0, 0]]

使用numpy.squeeze你可以做你想做的事:

import numpy as np

a = np.array([[[0, 1, 0, 1, 0]],
              [[1, 1, 1, 1, 1]],
              [[1, 0, 0, 1, 1]],
              [[0, 1, 0, 0, 0]]])

a.squeeze()

[[0 1 0 1 0]
 [1 1 1 1 1]
 [1 0 0 1 1]
 [0 1 0 0 0]]