首页 > 解决方案 > 如何仅使用递归通过python从列表中删除项目

问题描述

如何仅使用没有循环的递归和任何内置方法或函数在 python 中编写代码?我试过:

def myRemove(x, cont): # x is a string inside of the list cont
    if x == cont:
        return None
    elif len(x) > len(cont):
        return None
    else:
        if "x" not in cont[0]:
            return myRemove(x,cont[1:])
        else:
            return cont

标签: pythonrecursion

解决方案


我在您的代码中看到的一些问题:

1.字符串和变量的区别

您的代码中有以下行在语义上是错误的:

if "x" not in cont[0]:
    ...

"x"是字符串 'x' 而不是 的值x。要解决此问题,请删除引号。

if x not in cont[0]:
    ...

2.列表和变量的区别

要检查变量是否在列表中,请使用in. 例如

>>> "test" in ["test", "wow", "u"]
true

要检查一个变量是否等于另一个变量,请使用==. 例如

>>> "test" == ["test", "wow", "u"][0]
true

代码的固定部分:(因为cont[0]返回一个值而不是列表)

if x == cont[0]:
    ...

3. 递归返回

您必须将返回的列表与另一个列表之前的列表部分连接起来。否则,您总是返回列表的最后一部分。

一种可能的解决方案

def remove(string, string_list):
    if string_list[0] == string:
        return string_list[1:]
    else:
        return string_list[:1] + remove(string,string_list[1:])

推荐阅读