List 用于修改列表的python递归帮助
我有一段代码,可以用另一个子字符串替换一个字符串的现有子字符串。我想修改它,以便它可以为列表工作,但我不知道如何做。换句话说,我想修改它,这样它就可以用新元素替换列表中的一个现有元素。我想递归地这样做List 用于修改列表的python递归帮助,list,python-3.x,recursion,elements,List,Python 3.x,Recursion,Elements,我有一段代码,可以用另一个子字符串替换一个字符串的现有子字符串。我想修改它,以便它可以为列表工作,但我不知道如何做。换句话说,我想修改它,这样它就可以用新元素替换列表中的一个现有元素。我想递归地这样做 def rec_replace(string, a, b): if not string: #if the string is empty return "" elif string[:len(b)] == b: #if the string start with
def rec_replace(string, a, b):
if not string: #if the string is empty
return ""
elif string[:len(b)] == b: #if the string start with b, replace it with a
return a + rec_replace(string[len(b):], a, b)
else: #else, add this character and go to the next one
return string[0] + rec_replace(string[1:], a, b)
你在瞎混。只需使用:
lst[lst.index(old_element)]=new_element
如果要替换旧元素的所有引用,请使用循环:
while old_element in lst:
lst[lst.index(old_element)]=new_element
对于字符串,只需使用:
string.replace(old_element,new_element)
你在瞎混。只需使用:
lst[lst.index(old_element)]=new_element
如果要替换旧元素的所有引用,请使用循环:
while old_element in lst:
lst[lst.index(old_element)]=new_element
对于字符串,只需使用:
string.replace(old_element,new_element)