Python 返回(递归)更改的列表?
我希望获取一个列表Python 返回(递归)更改的列表?,python,list,recursion,Python,List,Recursion,我希望获取一个列表list=[3,2,1,3,2,1],并对每个项目递归检查该项目是否为a值,如果是,则在列表的副本中将该值替换为b,并返回该副本。 这是我目前的代码: def replace(list,a,b): #base case 1: list is empty if list==[]: return list #case 1: the first character is a elif list[0] == a: list
list=[3,2,1,3,2,1]
,并对每个项目递归检查该项目是否为a
值,如果是,则在列表的副本中将该值替换为b
,并返回该副本。
这是我目前的代码:
def replace(list,a,b):
#base case 1: list is empty
if list==[]:
return list
#case 1: the first character is a
elif list[0] == a:
list[0] = b
return replace(list[1:],a,b)
#case 2: the first character is not a
elif list[0]!=a:
return replace(list[1:],a,b)
return list
我的问题是,我(打印了每个递归,打印语句因简短而被删除了))此代码的输出如下所示:
[3,2,1,3,2,1]
[2,1,3,2,1]
[4,3,2,1]
[3,2,1]
[2,1]
[4]
我想要的结果是:
[3,2,4,3,2,4]
我不知道如何得到所说的输出 再次调用replace时,您错过了第一个元素。只需将第一个元素附加到结果的前面
def replace(thelist,a,b):
#base case 1: thelist is empty
if thelist==[]:
return thelist
#case 1: the first character is a
elif thelist[0] == a:
thelist[0] = b
return thelist[:1] + replace(thelist[1:], a, b)
print replace([3,2,1,3,2,1], 1, 4)
再次调用replace时,您错过了第一个元素。只需将第一个元素附加到结果的前面
def replace(thelist,a,b):
#base case 1: thelist is empty
if thelist==[]:
return thelist
#case 1: the first character is a
elif thelist[0] == a:
thelist[0] = b
return thelist[:1] + replace(thelist[1:], a, b)
print replace([3,2,1,3,2,1], 1, 4)
不带递归的相同结果:
def replace_list(thelist,a,b):
return [ b if l == a else l for l in thelist ]
print replace_list([3,2,1,3,2,1], 1, 4)
输出:
[3, 2, 4, 3, 2, 4]
不带递归的相同结果:
def replace_list(thelist,a,b):
return [ b if l == a else l for l in thelist ]
print replace_list([3,2,1,3,2,1], 1, 4)
输出:
[3, 2, 4, 3, 2, 4]
你需要一个循环来迭代列表中的元素,并检查每个元素=a有没有一种不用for循环的方法?jjb:这是一个不同的问题。你使用a
&b
的哪些值来调用函数replace
?递归不是一个好主意你需要一个循环来迭代列表中的元素列出并检查每个元素=a有没有一种不用for循环的方法?jjb:这是一个不同的问题。a
和b
的哪些值用于调用函数replace
?递归并不是一个好主意。将参数重命名为类似元素的东西也很好,condition\u value
,replacement\u value
将参数重命名为元素
,condition\u value
,replacement\u value