Help me please with this problem: I have a list containing numbers and lists kind of:
list = [1,2,[3,4,5],6,7,[8,9]]
What I want to get is a list of just numbers (mergin included lists in parent list): Example:
new_list = [1,2,3,4,5,6,7,8,9]
Help me please with this problem: I have a list containing numbers and lists kind of:
list = [1,2,[3,4,5],6,7,[8,9]]
What I want to get is a list of just numbers (mergin included lists in parent list): Example:
new_list = [1,2,3,4,5,6,7,8,9]
Using recursion and collections.Iterable
:
>>> from collections import Iterable
>>> def flat(lst):
... for parent in lst:
... if not isinstance(parent, Iterable):
... yield parent
... else:
... for child in flat(parent):
... yield child
...
>>> list(flat(t))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Just remember to not name lists after their own type :).
I personally use this method :
This is a functional version of recursive flatten which handles both tuples and lists, and lets you throw in any mix of positional arguments. Returns a generator which produces the entire sequence in order, arg by arg:
flatten = lambda *n: (e for a in n
for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,)))
Usage:
l1 = ['a', ['b', ('c', 'd')]]
l2 = [0, 1, (2, 3), [[4, 5, (6, 7, (8,), [9]), 10]], (11,)]
print list(flatten(l1, -2, -1, l2))
['a', 'b', 'c', 'd', -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
This works fine with both python 3.x and python 2.x
Here is a regex solution for the same ..
import re
def Flatten(TheList):
a = str(TheList)
b,crap = re.subn(r'[\[,\]]', ' ', a)
c = b.split()
d = [int(x) for x in c]
return(d)