'write a program which turns a n-dimensional array or list with maximum n number of list nested to a single dimension or flat list [duplicate]
How to convert a list like this :
[[1,[2,["s",2],3]],[1,2,3,4,5,6],532, "Potato", [23, [[[1,[4,[2,[]],[0],[0], [0]]], 234, 1222], "22More"]]]
to
[1, 2, 's', 2, 3, 1, 2, 3, 4, 5, 6, 532, 'Potato', 23, 1, 4, 2, 0, 0, 0, 234, 1222, '22More']
I have tried using a for loop and then unpacking them using that but it didn't work out. Now I thought I could make variables of the element in the master list and then try unpacking them but it is not happing the way I want
Please do help
Solution 1:[1]
you can use a recursive function to do that:
>>> list1 = [[1, [2, ['s', 2], 3]], [1, 2, 3, 4, 5, 6], 532, 'Potato', [23, [[[1, [4, [2, []], [0], [0], [0]]], 234, 1222], '22More']]]
>>> def listelements(mylist):
... rslt = []
... for value in mylist:
... if isinstance(value,list):
... rslt.extend(_listconc(value))
... else:
... rslt.append(value)
... return rslt
...
>>> listelements(list1)
[1, 2, 's', 2, 3, 1, 2, 3, 4, 5, 6, 532, 'Potato', 23, 1, 4, 2, 0, 0, 0, 234, 1222, '22More']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | XxJames07- |
