递归删除列表元素 Python [英] Recursion removing list elements Python
问题描述
需要编写一个递归函数来删除列表中的元素但保留结果中的数组,例如.
need to write a recurive function to remove elements of list but keep the arrays in the result such as.
def remove_words(listx):
for element in listx:
if isinstance(element, list):
remove_words(element)
else:
listx.remove(element)
return listx
remove_words(["a", "b", ["c"]])
将返回 [[]]
由于某种原因,我的代码返回 ["b",[]]
缺少一个元素.
My code returns ["b",[]]
for some reason it's missing an element.
推荐答案
迭代时不要从集合中移除元素.重复调用 list.remove
在性能方面也不是理想的,因为每次删除(从随机索引)都是 O(N)
.解决这两个问题的一个简单方法是以下理解:
Do not remove elements from a collection while iterating it. Repeated calls to list.remove
are also not ideal performance-wise since each removal (from a random index) is O(N)
. A simple way around both issues would be the following comprehension:
def remove_words(listx):
return [remove_words(e) for e in listx if isinstance(e, list)]
看似缺失的基本情况是一个没有嵌套列表的列表,其中返回一个空列表.
The seemingly missing base case is a list with no nested lists where an empty list is returned.
如果要就地修改列表,可以使用切片赋值:
If you want to modify the list in-place, you can use slice assignment:
def remove_words(listx):
listx[:] = [remove_words(e) for e in listx if isinstance(e, list)]
这篇关于递归删除列表元素 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!