我花了最后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
Run Code Online (Sandbox Code Playgroud)
我注意到的是函数中的参数'm'正在改变,好像是m_cloned的别名 - 但据我所知,我已经删除了函数第一行的别名.我在网上看到的任何其他地方似乎都暗示这一行会确保没有参数参考 - 但它不起作用.
我敢肯定我一定犯了一个简单的错误,但是2小时后我觉得我不会发现它.
看起来你需要一个深度复制,而不是浅拷贝,这是[:]给你的东西:
from copy import deepcopy
list2 = deepcopy(list1)
Run Code Online (Sandbox Code Playgroud)
这是一个比较两种类型副本的较长示例:
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
Run Code Online (Sandbox Code Playgroud)
输出:
[[1, 3], [1]] # list1
[[1, 3], [1]] # list2
[[1], [1]] # list3 - unaffected by reference-madness
Run Code Online (Sandbox Code Playgroud)