我正在开发一个程序,在这个程序中,我们有一个特定的列表,其中包含大量的无关嵌套,我们希望简化这些嵌套。
例如,一个输入可以是
[[['A', [[[[[[[[[['B', [[[[[[[[[['C', [[[[[[[[[['D']], [['E']], [['F', [[[[[[[[[['G']]]]]]]]]]]], [['H']], [['I']], [['J']]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
它应该输出
['A', ['B', ['C', [['D'], ['E'], ['F', ['G']], ['H'], ['I'], ['J']]]]]
但是,在运行了我的代码之后,它没有做任何事情并返回
[]
.
这是我的代码:
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