如何阻止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 个回答
1
使用 copy模块 来创建输入数据的深拷贝,使用 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)
在使用这个方法之前,先了解一下深拷贝可能会遇到的问题(可以查看上面的链接),确保这样做是安全的。
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,这样可以得到正确的结果。