Python: Flatten List Of Lists Of Lists
I know this has been asked before but I don't see any solutions for when there is a list of the type: original_list = [[1,2], [3], [4,5,[6]]] Tried this method: def flatten(list):
Solution 1:
Something along these lines?
In [6]: original_list = [[1,2], [3], [4,5,[6]]]
In [7]: def flatten(potential_list):
...: new_list = []
...: for e in potential_list:
...: if isinstance(e, list):
...: new_list.extend(flatten(e))
...: else:
...: new_list.append(e)
...: return new_list
...:
In [8]: flatten(original_list)
Out[8]: [1, 2, 3, 4, 5, 6]
Solution 2:
If you have nested-nested lists, the best way to flatten is using generator function
original_list = [[1,2], [3], [4,5,[6]]]
def flatten(l):
for i in l:
if isinstance(i,list):
yield from flatten(i)
else:
yield i
list(flatten(original_list))
#[1, 2, 3, 4, 5, 6]
Solution 3:
You can use Collections.Iterable
:
In [2810]: def flatten(x):
...: ifisinstance(x, collections.Iterable):
...: return [a for i in x for a in flatten(i)]
...: else:
...: return [x]
...:
In [2811]: flatten(original_list)
Out[2811]: [1, 2, 3, 4, 5, 6]
OR brute force like this:
In [2803]:flat_list= []
...:for sublist in original_list:...:for item in sublist:...:ifisinstance(item,list):...:for sub_item in item:...:flat_list.append(sub_item)...:else:...:flat_list.append(item)In [2804]:flat_listOut[2804]: [1, 2, 3, 4, 5, 6]
Solution 4:
Here's a recursive solution:
defrecursive_flatten(lst, retlist = []):
for item in lst:
iftype(item) isint:
retlist.append(item)
else:
recursive_flatten(item, retlist)
return(retlist)
Post a Comment for "Python: Flatten List Of Lists Of Lists"