gpt4 book ai didi

python - 删除引用/别名后,函数中传递的参数/参数仍在更改

转载 作者:太空狗 更新时间:2023-10-30 00:46:28 24 4
gpt4 key购买 nike

过去 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 小时后我想我找不到它了。

最佳答案

看起来你需要一个深拷贝,而不是浅拷贝,这就是 [:] 给你的:

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

关于python - 删除引用/别名后,函数中传递的参数/参数仍在更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8774166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com