我得到了一個使用遞回的任務,這樣任何給它的串列都會說 p 將在所需的輸出中回傳,如最后所示,而不會干擾或改變 p 的內容。當我運行這個函式時,它說區域變數 (y) 在沒有賦值的情況下被參考,即 len(y)==0 但我已經在函式 init 之外分配了 y。有人可以幫助確定出了什么問題嗎?
y=[] #To copy contents of x in it so that x is not modified
z=[] # To return it as a list required in the question
p=[1,2,3]
def inits(x):
if len(y)==0 and len(z)==0:
y=[i.copy for i in x] #Copying contents of x into x so that it remains unchanged
if len(z)==len(x) 1: #z list is one plus x list because it has [] in it
print(z)
else:
z.append(y.copy())
if len(y)!=0: #This is done so that when y=[] it does not return error for y.pop(-1)
y.pop(-1)
inits(x)
inits(p)
#Desired Output
[[1,2,3],[1,2],[1],[]]
uj5u.com熱心網友回復:
如果您不需要最后一個空元素,則可以隨意洗掉該else塊。對我來說也不需要
你的y變數
z = [] # To return it as a list required in the question
def foo(param):
if len(param):
z.append([i for i in param])
foo(param[0:-1])
else:
z.append([])
foo([1, 2, 3])
print(z)
[[1, 2, 3], [1, 2], [1], []]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396285.html
