需要编写一个递归函数来删除列表中的元素,但保留结果中的数组,例如。
def remove_words(listx):
for element in listx:
if isinstance(element, list):
remove_words(element)
else:
listx.remove(element)
return listxremove_words(["a", "b", ["c"]])将返回[[]]
由于某种原因,我的代码返回["b",[]],因为它缺少一个元素。
发布于 2018-01-09 17:52:50
在迭代集合时,不要从集合中移除元素。重复调用list.remove也不是理想的性能,因为每次删除(从随机索引中)都是O(N)。绕过这两个问题的一种简单方法是以下理解:
def remove_words(listx):
return [remove_words(e) for e in listx if isinstance(e, list)]看似缺少的基本情况是一个没有嵌套列表的列表,其中返回一个空列表。
如果要就地修改列表,可以使用切片指定:
def remove_words(listx):
listx[:] = [remove_words(e) for e in listx if isinstance(e, list)]发布于 2018-01-15 23:55:01
def remove_words(listx):
if listx == []:
return []
elif not isinstance(listx[0], list):
return remove_words(listx[1:])
else:
return [remove_words(listx[0])] + remove_words(listx[1:])
print(remove_words(["a", "b", ["c"]]))
print(remove_words(["a", ["b",["c","d"],"c"], [["f"],["g"]],"h"]))https://stackoverflow.com/questions/48165235
复制相似问题