使用递归遍历列表
我该如何用递归来写这个相同的函数呢?
def replace(thelist,a,b):
"""Returns: a COPY of thelist but with all occurrences of a replaced by b.
Example: replace([1,2,3,1], 1, 4) = [4,2,3,4].
Precondition: thelist is a list of ints
a and b are ints"""
我觉得我应该先复制一份原来的,然后再在列表中把 a 变成 b,但我不知道该怎么实现。请帮我解决这个问题,谢谢!
1 个回答
0
试试这个:
def replace(thelist, a, b):
if not thelist:
return []
elif thelist[0] == a:
return [b] + replace(thelist[1:], a, b)
else:
return [thelist[0]] + replace(thelist[1:], a, b)
这是一个递归的解决方案,效果如预期:
replace([1, 2, 3, 1], 1, 4)
=> [4, 2, 3, 4]