在python函数中使用列表
我无法理解下面的代码中发生了什么在python函数中使用列表,python,python-2.7,Python,Python 2.7,我无法理解下面的代码中发生了什么 #swaps list in index 1 L=[[1,2],[3,4]] def swap(X): beta=X[:] beta[1][0],beta[1][1]=beta[1][1],beta[1][0] return beta def code(W): alpha=W[:] print swap(alpha) return swap(alpha) print code(L) 它给出一个输出 [[1, 2], [4, 3]] [[
#swaps list in index 1
L=[[1,2],[3,4]]
def swap(X):
beta=X[:]
beta[1][0],beta[1][1]=beta[1][1],beta[1][0]
return beta
def code(W):
alpha=W[:]
print swap(alpha)
return swap(alpha)
print code(L)
它给出一个输出
[[1, 2], [4, 3]]
[[1, 2], [3, 4]]
在我期待的时候
[[1, 2], [4, 3]]
[[1, 2], [4, 3]]
原因是
alpha = W[:] # and also beta=X[:]
仅创建列表的浅拷贝。这意味着实际上只复制了外部列表。该外部列表再次包含对更多列表的引用-这些列表不在复制中(仅对它们的引用)
因此,您的副本alpha
和beta
总是引用相同的嵌套列表,并交换这些列表中的元素。这就是为什么您可以在调用后看到交换发生两次
swap(alpha)
两次
如果要进行深度复制,可以使用copy
模块进行写入
alpha = copy.deepcopy(W) # instead of alpha = W[:]
及
这样做将为您提供预期的输出:
[[1, 2], [4, 3]]
[[1, 2], [4, 3]]
可能重复的
[[1, 2], [4, 3]]
[[1, 2], [4, 3]]