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

标签 python

过去 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/

相关文章:

Python **kwargs : unexpected keyword argument

python - 您可以使用 FileZilla 部署 Flask 应用程序吗?

python - 如何计算numpy数组的两行之间的欧氏距离

python - 在 IPython Notebook 中更改绘图窗口大小

python - 如何在没有 `-` 或 `--` 之前进行参数?

javascript - 向文本子字符串添加新元素

python - 哪个更基本 : Python functions or Python object-methods?

python - Scala中的切片符号?

python - 如何以更英文的形式输出列表(如 "a, b and c")?

python - 如何解决 'django_content_type already exists' ?