I have a nested list with elements that are lists themselves. I want to find all the sublists and flatten them as a single list:
For example:
[[a], [b,[c,[d,e]]], [f,g]]
I want to have a list containing all existing sublists (flattened) in the original list, that is:
[[a], [b,c,d,e], [c,d,e], [d,e], [f,g]]
I used a recursive function but the problem is that I get nested sublists again which is not what I want. Also my question is not about flattening irregular lists.
We'll use a helper function that returns the flattened form of a nested list and all sublists:
def flattened_list_and_sublists(l):
# First return value is l, flattened.
# Second return value is a list of flattened forms of all nested sublists
# of l.
flattened = []
flattened_sublists = []
for i in l:
if isinstance(i, list):
i_flattened, i_flattened_sublists = flattened_list_and_sublists(i)
flattened += i_flattened
flattened_sublists.append(i_flattened)
flattened_sublists += i_flattened_sublists
else:
flattened.append(i)
return flattened, flattened_sublists
Then the function you want returns the second return value of the above function:
def all_flattened_sublists(l):
l_flattened, l_sublists_flattened = flattened_list_and_sublists(l)
return l_sublists_flattened
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.