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

Python 删除引用/别名后,仍在更改函数中传递的参数/参数,python,Python,我在这上面花了2个小时,我可能已经阅读了这里所有关于传递给函数的变量的问题。我的问题是受函数内部更改影响的参数/参数的常见问题,尽管我已通过在函数中使用variable\u cloned=variable[:]在没有引用的情况下复制内容来删除引用/别名 代码如下: def add_column(m): #this should "clone" m without passing any reference on m_cloned = m[:] for in

我在这上面花了2个小时,我可能已经阅读了这里所有关于传递给函数的变量的问题。我的问题是受函数内部更改影响的参数/参数的常见问题,尽管我已通过在函数中使用
variable\u 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_的别名一样-但据我所知,我已删除了函数第一行的别名。我在网上看到的其他地方似乎都表明,这行代码将确保没有参数引用,但它不起作用


我肯定我犯了一个简单的错误,但两个小时后我想我找不到了。

看起来你需要的是深度拷贝,而不是浅拷贝,
[:]
给了你:

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

“…即使我已通过在函数中使用variable_cloned=variable[:]删除了引用/别名,以便在没有引用的情况下复制内容。”这使得
variable_cloned
引用了一个与
variable
不同的列表,但这两个列表将包含相同的内容:引用三个(2项)清单。哇,谢谢,我一个人永远不会到那里。我正在研究这一点,它似乎在某种程度上解释了深度复制和浅层复制之间的区别,但我不确定这实际上意味着什么——我是否应该在每次向函数传递变量时都进行深度复制?@FiveAlive不一定。有时您希望保留对“子”对象的引用。有时这并不重要(在处理不可变的“子项”时),因为字符串/整数之类的东西不能更改值,而是被新的副本替换,这在您的情况下不是问题。“知道”是成功的一半(他们说),现在你知道了,我相信你下次会更加关注你的需要。