gpt4 book ai didi

python - python 中的递归函数,返回作为参数给出的列表的副本,其中 a 被 b 替换,并且不会更改作为参数给出的列表

转载 作者:行者123 更新时间:2023-11-30 23:31:33 25 4
gpt4 key购买 nike

我正在尝试编写一个递归函数,它将接受一个数字列表和两个整数 a 和 b,并返回该列表的副本 - 但在这个副本中,作为参数给出的数字列表中的所有 a 将被替换为b。我已经编写了这段代码,但是从 shell 运行后,它显示“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]]).append(replace(thelist[1:],a,b))

最佳答案

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)

关于python - python 中的递归函数,返回作为参数给出的列表的副本,其中 a 被 b 替换,并且不会更改作为参数给出的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19834554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com