即使在使用递归时追加也得到空列表
getting empty list even though appending while using recursion
我试图在代码中打印列表“l”的所有子序列,但在这里我希望答案存储在“proc”中list.But当执行下面的代码时,我得到的是空列表list.I 正在练习递归 problems.I 无法理解为什么我得到的是“proc”列表的空列表
proc = [] #global array
def fun(t,lst,i,n):
if(i==n):
print(t)
proc.append(t) #appending to the global array
return
t.append(lst[i])
fun(t,lst,i+1,n)
t.pop()
fun(t,lst,i+1,n)
arr = [6,4,2]
n = len(arr)
l = []
for i in range(n):
for j in range(i+1,n):
l.append([i+1,j+1])
fun([],l,0,len(l))
print(proc) #printing the global list proc after executing function```
I want to know why i am getting output as empty lists even though i am appending "t" list to the "proc" list
[[1, 2], [1, 3], [2, 3]]
[[1, 2], [1, 3]]
[[1, 2], [2, 3]]
[[1, 2]]
[[1, 3], [2, 3]]
[[1, 3]]
[[2, 3]]
[]
[[], [], [], [], [], [], [], []]
i want answer to be appended list of t
您已陷入经典 Python 错误之一。您将 []
作为 t
传递给函数。然后修改 t
,并将 t
传递给递归调用。这意味着只有一个列表 t
。当您执行 proc.append(t)
时,您并不是在抓取数组的快照。您正在向该列表附加多个引用。到函数结束时,t
为空,因此您的 proc
有多个对空列表的引用。
短期修复是更改为
proc.append( t.copy() )
或
proc.append( t[:] )
我试图在代码中打印列表“l”的所有子序列,但在这里我希望答案存储在“proc”中list.But当执行下面的代码时,我得到的是空列表list.I 正在练习递归 problems.I 无法理解为什么我得到的是“proc”列表的空列表
proc = [] #global array
def fun(t,lst,i,n):
if(i==n):
print(t)
proc.append(t) #appending to the global array
return
t.append(lst[i])
fun(t,lst,i+1,n)
t.pop()
fun(t,lst,i+1,n)
arr = [6,4,2]
n = len(arr)
l = []
for i in range(n):
for j in range(i+1,n):
l.append([i+1,j+1])
fun([],l,0,len(l))
print(proc) #printing the global list proc after executing function```
I want to know why i am getting output as empty lists even though i am appending "t" list to the "proc" list
[[1, 2], [1, 3], [2, 3]]
[[1, 2], [1, 3]]
[[1, 2], [2, 3]]
[[1, 2]]
[[1, 3], [2, 3]]
[[1, 3]]
[[2, 3]]
[]
[[], [], [], [], [], [], [], []]
i want answer to be appended list of t
您已陷入经典 Python 错误之一。您将 []
作为 t
传递给函数。然后修改 t
,并将 t
传递给递归调用。这意味着只有一个列表 t
。当您执行 proc.append(t)
时,您并不是在抓取数组的快照。您正在向该列表附加多个引用。到函数结束时,t
为空,因此您的 proc
有多个对空列表的引用。
短期修复是更改为
proc.append( t.copy() )
或
proc.append( t[:] )