Recursion removing list elements Python

不羁岁月 提交于 2019-12-24 22:45:25

问题


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"]]) would return [[]]

My code returns ["b",[]] for some reason it's missing an element.


回答1:


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)]



回答2:


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/recursion-removing-list-elements-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!