【问题标题】:python recursion help for modifying lists修改列表的python递归帮助
【发布时间】:2016-03-06 07:54:07
【问题描述】:

我有这段代码可以用另一个子字符串替换一个字符串的现有子字符串。我想修改它,以便它可以用于列表,但我不知道该怎么做。换句话说,我想修改它,以便它可以用新元素替换列表中的现有元素。我想递归地做。

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)

【问题讨论】:

    标签: list python-3.x recursion elements


    【解决方案1】:

    你白费心机。只需使用:

    lst[lst.index(old_element)]=new_element
    

    如果您希望它替换所有出现的 old_element,请使用循环:

    while old_element in lst:
        lst[lst.index(old_element)]=new_element
    

    对于字符串,只需使用:

    string.replace(old_element,new_element)
    

    【讨论】:

      猜你喜欢
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多