Python 使用递归函数反转字符串列表
我正在尝试使用递归函数反转列表。不幸的是,我对递归相当陌生。这可能吗?到目前为止,这是我的代码Python 使用递归函数反转字符串列表,python,recursion,python-3.x,Python,Recursion,Python 3.x,我正在尝试使用递归函数反转列表。不幸的是,我对递归相当陌生。这可能吗?到目前为止,这是我的代码 def stringRev (word): worLen = len(word) if worLen == 1: return word return (word[-1]) + stringRev(word[:-1]) listWord = ["hey", "there", "jim"] print(stringRev(listWord)) 要反转列表元素的
def stringRev (word):
worLen = len(word)
if worLen == 1:
return word
return (word[-1]) + stringRev(word[:-1])
listWord = ["hey", "there", "jim"]
print(stringRev(listWord))
要反转列表元素的顺序,请更改:
return (word[-1]) + stringRev(word[:-1])
到
(注意方括号)
问题是您试图将字符串(word[-1]
)与列表(word[:-1]
)连接起来
问题是您的函数只需要一个单词,而您却用一个单词列表来调用它
如果您按如下方式调用它,您将看到它工作得很好:
for word in ["hey", "there", "jim"]:
print(stringRev(word))
或者,如果希望在列表中存储反向字符串:
l = [stringRev(w) for w in ["hey", "there", "jim"]]
函数失败的一种情况是空字符串。我不知道这是否是一个有效的输入,因此这可能不是问题(但修复起来却很简单)。如果您想在Python中完成它:
reversed(listWord)
假设word是一个列表或元组
要获取列表,请执行以下操作:
list(reversed(listWord))
应该有用
但是如果你想要一个算法,我想那不是你的朋友 您的问题是
(word[-1])
是字符串,而不是列表。因此,您正在尝试添加/连接字符串和列表。我将该表达式更改为[word[-1]]
以创建一个列表
>>> def stringRev (word):
... worLen = len(word)
... if worLen == 1:
... return word
... return [word[-1]] + stringRev(word[:-1])
...
>>> listWord = ["hey", "there", "jim"]
>>> print(stringRev(listWord))
['jim', 'there', 'hey']
>>>
另外,如果您在运行代码时包含收到的错误,这将非常有帮助:
TypeError:无法将“list”对象隐式转换为str
您的函数正常工作。函数的输入错误。请注意,reversed
不返回字符串。它为您提供了一个可编辑的对象。由于这个原因,您经常会看到s[::-1]
也会反转序列
>>> def stringRev (word):
... worLen = len(word)
... if worLen == 1:
... return word
... return [word[-1]] + stringRev(word[:-1])
...
>>> listWord = ["hey", "there", "jim"]
>>> print(stringRev(listWord))
['jim', 'there', 'hey']
>>>