Python 3.x 列表中的查找和替换功能有问题

Python 3.x 列表中的查找和替换功能有问题,python-3.x,Python 3.x,我的代码: def findAndReplace(orig, toFind, replacement): while orig.count(toFind) != 0: idx = orig.index(toFind) orig.remove(toFind) orig.insert(idx, replacement) rLst = findAndReplace(orig, toFind, replacement)

我的代码:

def findAndReplace(orig, toFind, replacement):
    while orig.count(toFind) != 0:
        idx = orig.index(toFind)
        orig.remove(toFind)
        orig.insert(idx, replacement)
        rLst = findAndReplace(orig, toFind, replacement)
        
        return (rLst)

    return orig

#我需要一个for或while循环,用于查找项目并用替换值替换它。我递归地得到了替换项,但我需要它成为一个循环。另外,包含替换项的列表将返回给before和after列表。有人知道我如何解决这个问题吗?

您的代码的问题是它使用了while循环,而且它也是递归的。在while循环中,函数将使用相同的精确参数再次调用,从而生成一个无用的循环。此外,函数在到达第一个“return”语句时停止,因此
return orig
语句将永远不会执行

更好的方法是使用for循环:

def findAndReplace(orig, toFind, replacement):
    for i, element in enumerate(orig):
        if element == toFind:
            orig[i] = replacement
    return orig
使用带有枚举函数的for循环,可以获得列表的每个元素及其索引。该函数遍历整个列表,检查它当前所在的元素是否是要替换的元素,如果是,则替换它。这样,列表中与toFind参数匹配的每个元素都将被替换。 但是,请确保不要在字符串上使用此函数,因为它们是不可变的,所以会出现错误

另一种方法是使用列表理解:

def findAndReplace(orig, toFind, replacement):
    return [replacement if element == toFind else element for element in orig]
在上述任何一种情况下,函数都会返回一个带有替换值的新列表,因此使用此函数的示例如下所示:

a = ["pizza", "pasta", "replaceme"]
a = findAndReplace(a, "replaceme", "spaghetti")

我把你的代码改了一点

def findAndReplace(orig, toFind, replacement, ret_orig=0):
    while orig.count(toFind) != 0:
        idx = orig.index(toFind)
        orig.remove(toFind)
        orig.insert(idx, replacement)
        rLst = findAndReplace(orig, toFind, replacement)
    if ret_orig == 1:
        return (rLst)
    else:
        return orig

list = ["awdr", "oper", "thr", "oper"]
print(findAndReplace(list, "oper", "repo"))
但除此之外,回报是好的! 或者你可以用

def findAndReplace(orig, toFind, replacement):
    rLst = str()
    while orig.count(toFind) != 0:
        idx = orig.index(toFind)
        orig.remove(toFind)
        orig.insert(idx, replacement)
        rLst = findAndReplace(orig, toFind, replacement)
    return [orig, rLst]


list = ["awdr", "oper", "thr", "oper"]
print(findAndReplace(list, "oper", "repo")[0])
请注意,我使用了[0]来表示return me(被替换的列表)或return of findandplace的第一项