【发布时间】:2016-02-24 20:06:21
【问题描述】:
我正在尝试以递归方式从嵌套列表中删除所有空列表。
def listcleaner(lst):
if isinstance(lst[0], int):
return listcleaner(lst[1:])
if isinstance(lst[0], list):
if len(lst[0]) == []:
lst[0].remove([])
return listcleaner(lst)
return listcleaner(lst[0])
return lst
我想要这个函数做的是
>>> a = listcleaner([1, [], [2, []], 5])
>>> print(a)
[1, [2], 5]
【问题讨论】:
-
您当前的代码有什么问题?
-
>>> listcleaner([1, [2, []], []]) 它会运行并让我回到多行,然后说列表索引超出范围
-
这不是一个合适的问题。你不能对技术有偏见。这是编程!