简体   繁体   English

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

[英]Flatten 3d list to 2d in python

So I have a list of lists in python that is something like this: 所以我在python中有一个列表列表,就像这样:

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

I want to flatten this list and end up with this: 我想弄平这个列表并以这个结尾:

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

Is there a straightforward way to do this in python? 有没有一种简单的方法可以在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]     

output 产量

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

Using numpy.squeeze you can do what you want: 使用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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM