Reputation: 75
I am working on a program where we have have a certain list with a lot of extraneous nesting, which we want to simplify.
For example, one input could be
[[['A', [[[[[[[[[['B', [[[[[[[[[['C', [[[[[[[[[['D']], [['E']], [['F', [[[[[[[[[['G']]]]]]]]]]]], [['H']], [['I']], [['J']]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
and it should output
['A', ['B', ['C', [['D'], ['E'], ['F', ['G']], ['H'], ['I'], ['J']]]]]
However, after running my code, it is not doing anything and returning []
.
Here is my code:
def clean_list(list2):
for item in list2:
if isinstance(item, list) and len(list2)==1: # this is an extraneous list!
item = clean_list(item)
list2.append(item[0].copy())
list2.remove(item)
return list2
Upvotes: 3
Views: 128
Reputation: 106768
You can use a function that recursively de-nests each item in the given list, but passes the sub-list to the recursive call if the list has only one item and that item is a list:
def denest(lst):
if isinstance(lst, list):
if len(lst) == 1 and isinstance(lst[0], list):
return denest(lst[0])
return [denest(i) for i in lst]
return lst
so that given your sample list stored in variable lst
, denest(lst)
would return:
['A', ['B', ['C', [['D'], ['E'], ['F', ['G']], ['H'], ['I'], ['J']]]]]
Upvotes: 4