Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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中的递归函数,该函数返回作为带';s替换为b';s并不会更改作为参数给出的列表_Python_List_Recursion - Fatal编程技术网

python中的递归函数,该函数返回作为带';s替换为b';s并不会更改作为参数给出的列表

python中的递归函数,该函数返回作为带';s替换为b';s并不会更改作为参数给出的列表,python,list,recursion,Python,List,Recursion,我正在尝试编写一个递归函数,它将接受一个数字列表和两个整数a和b,并返回列表的一个副本-但是在这个副本中,作为参数给出的数字列表中的所有a都将被b替换。我已经编写了这段代码,但是在从shell运行之后,它显示为“None”(不带双引号) 给出: [10, 2, 3, 10, 3, 4, 10, 2] 只需使用“+”而不是.append。由于[10].append([2])返回None,所以您没有得到任何结果 def replace(thelist,a,b): assert type(the

我正在尝试编写一个递归函数,它将接受一个数字列表和两个整数a和b,并返回列表的一个副本-但是在这个副本中,作为参数给出的数字列表中的所有a都将被b替换。我已经编写了这段代码,但是在从shell运行之后,它显示为“None”(不带双引号)

给出:

[10, 2, 3, 10, 3, 4, 10, 2]

只需使用“+”而不是.append。由于[10].append([2])返回None,所以您没有得到任何结果

def replace(thelist,a,b):

 assert type(thelist)==list, `thelist` + ' is not a list'

 assert type(a)==int, `a` + ' is not an integer'

 assert type(b)==int, `b` + ' is not an integer'
 if len(thelist)==0:
     return []
 return ([b] if thelist[0]==a else [thelist[0]])+replace(thelist[1:],a,b)

请注意,
`backtick`
语法被弃用,取而代之的是
repr(backtick)
语法,
len(thelist)==0
是非语法化的,最好拼写
而不是列表
最后的挑剔:您不应该在这里进行类型检查,至少不适用于
a
b
-没有理由将您的功能限制为
int
s
[10, 2, 3, 10, 3, 4, 10, 2]
def replace(lst, a, b):
    if not lst:
        return []
    head, tail = lst[0], lst[1:]
    return [b if head == a else head] + replace(tail, a, b)
def replace(thelist,a,b):

 assert type(thelist)==list, `thelist` + ' is not a list'

 assert type(a)==int, `a` + ' is not an integer'

 assert type(b)==int, `b` + ' is not an integer'
 if len(thelist)==0:
     return []
 return ([b] if thelist[0]==a else [thelist[0]])+replace(thelist[1:],a,b)