Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 用于修改列表的python递归帮助_List_Python 3.x_Recursion_Elements - Fatal编程技术网

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)