Reputation: 469
Having this list
l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
I would like to get a function extracting all nested lists and return
l = [['a', 'b', 'c', 'd'],["d","d"],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]
like flatten but keeping the list formation of every nested list. This is the closest I have been and I feel like there is a way of accomplishing my goal without using an extra structure to filter duplicates. Also, order matters in string and list level.
def get_all_nested_list(l,returned_list):
nested_list = l
while isinstance(nested_list, list):
for elem in nested_list:
get_all_nested_list(elem,returned_list)
if isinstance(nested_list[0], str):
returned_list.append(nested_list)
nested_list = nested_list[0]
if __name__ == '__main__':
l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
l2 = []
get_all_nested_list(l,l2)
print(l2)
Any other ways of doing it the above either by using itertools or suggesting an actually proper way of using yield instead of passing another list as argument are more than welcome.
Upvotes: 2
Views: 1646
Reputation: 376
You can do it like this:
from itertools import chain
my_nested_list = [['a', 'b', 'c', 'd'],['e', ['r'], [["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
def flatten(nested_list):
for item in nested_list:
if not isinstance(item,list):
yield item
elif list(chain(*item)) == item:
yield item
else:
yield from flatten(item)
flat_list = list(flatten(my_nested_list))
# [['a', 'b', 'c', 'd'], 'e', ['r'], ['d', 'd'], ['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]
Thanks
Upvotes: 1
Reputation: 1066
You could try a recursive function
my_nested_list = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
def flatten(nested_list):
for item in nested_list:
if not isinstance(item[0],list):
yield item
else:
yield from flatten(item)
flat_list = [item for item in flatten(my_nested_list)]
print(flat_list)
Upvotes: 4