我有这个:
def ppend(n):
lis = []
if n.rest == None:
pass
else:
lis.append(n.first)
ppend(n.rest)
return lis
n 是一个链表 [1,2,3]
我得到的输出是:
[1]
但是我正在寻找的输出是:
[1,2,3]
最佳答案
您将在每次递归时创建一个新的 lis
列表。 (顺便说一句,您可能会尝试查找更具描述性的名称。)但是,仅返回第一个列表,因为您不对递归产生的其他列表执行任何操作。相反,您只需调用该函数,该函数只是创建一个新列表,而不对函数返回的值执行任何操作。您可以在以下行中看到这一点:
ppend(n.rest) # a new list is created but nothing is done with the result of the function
如果您只打算使用该函数一次,则只需将 lis
赋值移到函数之外即可:
lis = []
def ppend(n):
if n.rest is not None: # the first if statement appears unnecessary
lis.append(n.first)
ppend(n.rest)
return lis # or don't return it but simply refer to lis where you need to
但是,如果您计划多次使用该函数并且始终需要一个新列表,则上述方法将不起作用。在后一种情况下,您可以添加第二个函数,如下所示:
def make_ppend(n, lis): # add lis as a parameter to be explicit, but you could rely on scope instead of adding this extra parameter
if n.rest is not None:
lis.append(n.first)
make_ppend(n.rest, lis)
def ppend(n):
lis = [] # now in the local scope
make_ppend(n, lis)
return lis
我猜您正在寻找类似第二种解决方案的东西。
关于python - 使用递归将 LinkedLists 项目追加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26445967/