Skip to content Skip to sidebar Skip to footer

How To Convert 2d Nested Array Into 2d Array Single?

I have an array a as follow : [[(0,0),(2,0)],[(1,1)], [(3,8)]] So now I want to convert it like this: [(0,0),(2,0),(1,1), (3,8)] How may I do that? I had tried bellow code and su

Solution 1:

You can use reduce from functools like this

from functools import reduce

a = [[(0,0),(2,0)],[(1,1)], [(3,8)]]
res = reduce(lambda x,y: x+y,a)

print(res) # [(0, 0), (2, 0), (1, 1), (3, 8)]

Solution 2:

If your nested-deep is certain, you can use chain from itertools package

from itertools import chain

data = [[(0,0),(2,0)],[(1,1)], [(3,8)]]

result = list(chain(*data))

Solution 3:

You can use list comprehensions -

nested = [[(0,0),(2,0)],[(1,1)], [(3,8)]]
un_nested = [inside_element for element in nested for inside_element in element]
# Returns - [(0, 0), (2, 0), (1, 1), (3, 8)]

Post a Comment for "How To Convert 2d Nested Array Into 2d Array Single?"