另一個相關的問題是「How do I pass a variable by reference?」。Daren Thomas使用賦值來解釋變量傳遞如何在Python中工作。對於追加方法,我們可以用類似的方式來思考。假設你要追加列表「list_of_values」到列表「list_of_variables」,
list_of_variables = []
list_of_values = [1, 2, 3]
list_of_variables.append(list_of_values)
print "List of variables after 1st appending: ", list_of_variables
list_of_values.append(10)
list_of_variables.append(list_of_values)
print "List of variables after 2nd appending: ", list_of_variables
的追加操作,可以將它看作:
list_of_variables[0] = list_of_values --> [1, 2, 3]
list_of_values --> [1, 2, 3, 10]
list_of_variables[1] = list_of_values --> [1, 2, 3, 10]
由於第一和第二項「list_of_variables」指向在存儲器中的同一個對象,從上面的輸出是:
List of variabiles after 1st appending: [[1, 2, 3]]
List of variables after 2nd appending: [[1, 2, 3, 10], [1, 2, 3, 10]]
在另一方面,如果「列表_of_values「是一個變量,行爲會有所不同。
list_of_variables = []
variable = 3
list_of_variables.append(variable)
print "List of variabiles after 1st appending: ", list_of_variables
variable = 10
list_of_variables.append(variable)
print "List of variables after 2nd appending: ", list_of_variables
所附操作現在等效於:
list_of_variables[0] = variable --> 3
variable --> 4
list_of_variables[1] = variable --> 4
並且輸出是:
List of variabiles after 1st appending: [3]
List of variables after 2nd appending: [3, 10]
變量和list_of_values之間的差異是在就地後一個變化。
'condition'和'm'是什麼意思?什麼是'fi'?什麼是'f()'? – 2012-09-05 10:42:55
X根據函數進行更新, m是for循環的範圍, while循環運行任意數量的步驟 – abcd
但現在我很困惑,我看到你有'f1'和'fi'你的代碼中有一個錯字嗎? – zenpoy