如何阻止Python函数修改其输入?

时间:2010-07-04 05:56:47

标签: python

我刚刚问过这个问题,但修复不适用于x = [[]],我猜测是因为它是一个嵌套列表,这就是我将要使用的。

def myfunc(w):
 y = w[:]
 y[0].append('What do I need to do to get this to work here?')
 y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.')
 return y

x = [[]]
z = myfunc(x)
print(x)

2 个答案:

答案 0 :(得分:3)

以下是解决问题的方法:

def myfunc(w):
    y = [el[:] for el in w]
    y[0].append('What do I need to do to get this to work here?')
    y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.')
    return y

x = [[]]
z = myfunc(x)
print(x)

关于[:]的事情是,它是一个浅层副本。您还可以从copy模块导入deepcopy以获得正确的结果。

答案 1 :(得分:1)

使用copy module并使用deepcopy功能创建输入的深层副本。修改副本而不是原始输入。

import copy

def myfunc(w):
    y = copy.deepcopy(w)
    y[0].append('What do I need to do to get this to work here?')
    y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.')
    return y
x = [[]]
z = myfunc(x)
print(x)

在使用此方法之前,请阅读deepcopy的问题(​​查看上面的链接)并确保它是安全的。