我花了最后2个小时来讨论这个问题,我可能已经阅读了有关传递给函数的变量的所有问题。我的问题是参数/参数的常见问题受到函数内部所做更改的影响,即使我已经在函数中使用variable_cloned = variable[:]
删除了引用/别名,以便在没有引用的情况下复制内容。
以下是代码:
def add_column(m):
#this should "clone" m without passing any reference on
m_cloned = m[:]
for index, element in enumerate(m_cloned):
# parameter m can be seen changing along with m_cloned even
# though 'm' is not touched during this function except to
# pass it's contents onto 'm_cloned'
print "This is parameter 'm' during the for loop...", m
m_cloned[index] += [0]
print "This is parameter 'm' at end of for loop...", m
print "This is variable 'm_cloned' at end of for loop...", m_cloned
print "m_cloned is m =", m_cloned is m, "implies there is no reference"
return m_cloned
matrix = [[3, 2], [5, 1], [4, 7]]
print "\n"
print "Variable 'matrix' before function:", matrix
print "\n"
add_column(matrix)
print "\n"
print "Variable 'matrix' after function:", matrix
我注意到函数中的参数'm'正在改变,好像是m_cloned的别名 - 但据我所知,我已经删除了函数第一行的别名。我在网上看到的其他任何地方似乎都暗示这一行会确保没有参数参考 - 但它不起作用。
我确信我一定犯了一个简单的错误,但是2小时后我觉得我不会发现它。
答案 0 :(得分:9)
看起来你需要一个深度复制,而不是一个浅拷贝,这是[:]
给你的:
from copy import deepcopy
list2 = deepcopy(list1)
以下是比较两种类型副本的较长示例:
from copy import deepcopy
list1 = [[1], [1]]
list2 = list1[:] # while id(list1) != id(list2), it's items have the same id()s
list3 = deepcopy(list1)
list1[0] += [3]
print list1
print list2
print list3
输出:
[[1, 3], [1]] # list1
[[1, 3], [1]] # list2
[[1], [1]] # list3 - unaffected by reference-madness