【发布时间】: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.
我现在遇到的问题是:我注意到递归只会改变输入列表中的第一个元素,并且第一个元素之后的每个元素都不会受到突变的影响,我认为它可能与我传递给递归的新输入列表有关,但我不知道为什么这不起作用。
感谢您提前提供帮助。 :)
【问题讨论】: