另一个相关问题是“如何通过引用传递变量? ”。Daren Thomas 使用赋值来解释变量传递在 python 中是如何工作的。对于 append 方法,我们可以以类似的方式思考。假设您将列表“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]]
另一方面,如果“list_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]
variable 和 list_of_values 之间的区别在于后者就地更改。