我正试图以递归方式从嵌套列表中删除所有空列表。
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]
答案 0 :(得分:1)
每次返回时,您都要退出该功能。这是更新的代码:
def listcleaner(lst):
if not lst: # If list is empty
return [] # Go no further
if isinstance(lst[0], list):
if lst[0]: # If the list has something in it, we want to run listcleaner() on it.
return [listcleaner(lst[0])] + listcleaner(lst[1:])
else: # Otherwise, just skip that list
return listcleaner(lst[1:])
else:
return [lst[0]] + listcleaner(lst[1:]) # If it is not a list, return it unchanged plus listcleaner() on the rest.
a = listcleaner([1, [], [2, []], 5])
print(a)
输出:
[1, [2], 5]
答案 1 :(得分:0)
这样的东西?
def listcleaner(lst): result = [] for l in lst: if type(l) == list and len(l) > 0: result.append(listcleaner(l)) elif type(l) != list: result.append(l) return result
答案 2 :(得分:0)
def listcleaner(lst):
n=len(lst)
i=0
while i < n :
if isinstance(lst[i],list):
if len(lst[i])==0:
del lst[i]
n=len(lst)
else:
listcleaner(lst[i])
i=i+1
else:
i=i+1
return lst
a= listcleaner([1, [], [2, []], 5])
b= listcleaner([1,[],[2,[],[[],[],3]],5])
print(a)
print(b)
输出:
[1, [2], 5]
[1, [2, [3]], 5]
答案 3 :(得分:0)
希望这符合您的递归标准:
def listcleaner(lst, result=None):
if result is None:
result = []
if not isinstance(lst, list):
return lst
if not lst:
return result
head = listcleaner(lst[0])
if head != []:
result.append(head)
return listcleaner(lst[1:], result)
测试:
>>> listcleaner([])
[]
>>> listcleaner([1, [], [2, []], 5])
[1, [2], 5]
>>> listcleaner([1, [], [2, [], [[], [], 3]], 5])
[1, [2, [3]], 5]
警告:我不知道你想对[[[]]]
等嵌套案例做些什么。在“删除所有空列表”的一种解释中,由于只有最里面的列表为空,因此该函数应该删除它并返回[[]]
。另一种解释是我们应该继续前进,直到没有空列表,并返回[]
。我的解决方案是后者。 (说实话,还没找到办法做前者......)