简体   繁体   中英

Flatten 3d list to 2d in python

So I have a list of lists in python that is something like this:

[[[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?

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:

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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