【问题标题】:Recursion and List Mutation递归和列表变异
【发布时间】:2020-05-25 06:15:43
【问题描述】:

我限制自己仅使用递归来改变列表,这样做时我遇到了一些小麻烦。

def expand_strings(L,s,i):
    if len(L) == 0:
        return
    else:
        if len(L[0]) - 1 <= i:
            L[0] += s
        elif len(L[0]) - 1 > i:
            new_string = L[0][:i] + s + L[0][i:]
            L[0] = new_string
            expand_strings(L[1:], s, i)
            return

L:包含可能的 1 个或多个字符串的输入列表 s:我需要“插入”或“附加”到列表中的字符串元素的字符串的额外部分 i:我要插入或附加 s 的字符串的索引。

这个函数的主要目标如下:

1. if the index i within the range 0 ~ len(string_element_in_list), then I insert my s starting from index i


2. if the index i is larger than what the current string length, then I do the append s.

我现在遇到的问题是:我注意到递归只会改变输入列表中的第一个元素,并且第一个元素之后的每个元素都不会受到突变的影响,我认为它可能与我传递给递归的新输入列表有关,但我不知道为什么这不起作用。

感谢您提前提供帮助。 :)

【问题讨论】:

    标签: python recursion mutation


    【解决方案1】:

    问题在于递归调用expand_strings(L[1:], s, i)。当您使用切片获取列表的一部分时,python 会创建该子列表的全新副本。因此,递归调用会创建列表的副本,但第一个元素除外,并在该副本上工作。

    解决此问题的一种方法是从您的方法中返回修改后的列表:

    def expand_strings(L,s,i):
        if len(L) == 0:
            return []
        else:
            if len(L[0]) - 1 <= i:
                L[0] += s
            elif len(L[0]) - 1 > i:
                new_string = L[0][:i] + s + L[0][i:]
                L[0] = new_string
            return [L[0]] + expand_strings(L[1:], s, i)
    

    如果您不想每次都创建子列表的副本(并返回修改后的列表),您可以在方法中再添加一个参数来指定要修改的第一个元素的位置。基本情况是起始索引等于列表的长度。

    def expand_strings(L,s,i,start):
        if start == len(L):
            return
        if len(L[start]) - 1 <= i:
            L[start] += s
        else:
            L[start] = L[start][:i] + s + L[start][i:]
        expand_strings(L, s, i, start + 1)
    

    【讨论】:

    • 哦,我明白了,谢谢你的帮助。只是为了好奇,如果这个函数必须返回 None 怎么办?如果是这种情况,我是否仍然可以使用递归来做到这一点?
    • 在这种情况下,您将不得不对同一个列表进行操作。查看更新的答案。
    • 另外,@DigitalSoul,如果您想对列表中的每个字符串执行此操作,您需要将递归调用放在 else 块之外。
    猜你喜欢
    • 2017-06-24
    • 2011-12-22
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2015-04-27
    • 2021-12-16
    • 2015-10-30
    • 2016-10-21
    相关资源
    最近更新 更多