我正在嘗試在代碼中列印串列“l”的所有子序列,但在這里我希望將答案存盤在“proc”串列中。但是在執行下面的代碼時,我得到串列的空串列。我正在練習遞回問題.我堅持理解為什么我得到的串列是“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
uj5u.com熱心網友回復:
您已經成為經典 Python 錯誤之一的犧牲品。您將[]作為t. 然后修改t,并傳遞t給遞回呼叫。這意味著只有一個 LIST t。當你這樣做時proc.append(t),你并沒有抓取陣列的快照。您正在向該串列附加多個參考。到函式結束時,t它是空的,因此您proc有多個對空串列的參考。
短期解決方法是更改??為
proc.append( t.copy() )
或者
proc.append( t[:] )
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/425220.html
上一篇:如何將嵌套字典轉換為串列字串
