我有一个嵌套列表,其中包含列表本身的元素。我想找到所有的子列表并将它们展平为一个列表:
例如:
[[a], [b,[c,[d,e]]], [f,g]]
我希望在原始列表中有一个包含所有现有子列表(展平)的列表,即:
[[a], [b,c,d,e], [c,d,e], [d,e], [f,g]]
我使用了递归函数,但问题是我再次获得了嵌套的子列表,这不是我想要的。此外,我的问题不是关于flattening不规则名单。
答案 0 :(得分:1)
我们将使用一个辅助函数来返回嵌套列表的扁平形式和所有子列表:
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
然后你想要的函数返回上述函数的第二个返回值:
def all_flattened_sublists(l):
l_flattened, l_sublists_flattened = flattened_list_and_sublists(l)
return l_sublists_flattened