python - 如何仅使用递归通过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
解决方案
我在您的代码中看到的一些问题:
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:])
推荐阅读
- node.js - 没有连接的mongoDB搜索
- python - CherryPy 向 Flask 发布文件请求导致文件对象问题
- javascript - VueJS检查字符串是否包含v-btn标签中if语句中的子字符串
- angular - 在浏览器的控制台中停止无限错误循环
- python - 尝试从 macOS 上的 virtualenv 运行 pip 命令时出现 Pip 错误
- html - 电子定制通知设计
- javascript - 您可以在 Selenium webbrouser 中跟踪网页上的鼠标位置吗?C#
- javascript - JS 使用类和超时创建闪烁?
- spring-data-elasticsearch - 升级到spring boot 2.2.X后的MappingException(Attempt to add id)
- select - DataList:如何隐藏查找值?