Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用递归迭代列表_Python_List_Python 2.7_Recursion - Fatal编程技术网

Python 使用递归迭代列表

Python 使用递归迭代列表,python,list,python-2.7,recursion,Python,List,Python 2.7,Recursion,如何使用递归编写相同的函数 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""" 我相信我应该

如何使用递归编写相同的函数

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,但我不知道如何实现。请帮我解决这个问题,谢谢

试试这个:

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]

为什么它必须利用递归?你试过什么了吗?显示一些代码。这个问题是为了练习递归newlist=thelist[:]如果newlist=[]:返回0如果newlist[0]==a,则返回a=b如果newlist[0]==a,否则a+replacenewlist[1:],a,bI知道其中一些错误,但我不确定从哪里开始