0

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?

4
  • 1
    Could you share a more copy/paste friendly version of the lists? Commented Jul 12, 2019 at 11:00
  • please add commas Commented Jul 12, 2019 at 11:02
  • ok I changed the list with an easier example. Commented Jul 12, 2019 at 11:05
  • You need list(chain.from_iterable(l)) Commented Jul 12, 2019 at 11:08

2 Answers 2

2

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

@yatu I know, there is already answer for list, so I converted list to np.array
2
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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.