[英]Python: How do I avoid my global variable from being updated when passing it through a function?
以下是我的问题的简化版本:
example =[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
def func(data):
data[0][0:6] = [1, 1, 1, 1, 1]
data[1][0:6] = [1, 1, 1, 1, 1]
return data
print(example)
func(example)
print(example)
并具有 output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
我期待的 output 是:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
如何避免在运行“func”后更新全局变量“example”? 我已经尝试了一个数字占位符变量组合(“func”内部和外部)并且都具有相同的结果 - 一个更新的“示例”。
虽然您应该避免使用全局变量,但如果您绝对需要执行上述操作,请使用deepcopy()
:
from copy import deepcopy
example =[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
def func(data):
data = deepcopy(data)
data[0][0:6] = [1, 1, 1, 1, 1]
data[1][0:6] = [1, 1, 1, 1, 1]
return data
print(example)
func(example)
print(example)
尝试使用深拷贝:
import copy
example =[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
def func(data):
data[0][0:6] = [1, 1, 1, 1, 1]
data[1][0:6] = [1, 1, 1, 1, 1]
return data
print(example)
func(copy.deepcopy(example))
print(example)
因为列表是可变的,所以它们基本上是通过引用传递给func
的。 如果您想对该 object 的不同副本执行操作,则需要明确制作这样的副本(其他答案相同,但对于您的情况,您可能希望在函数中使用它):
import copy
example =[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
def func(data):
localdata = copy.deepcopy(data). ## or data.copy() or copy.copy(data)
localdata[0][0:6] = [1, 1, 1, 1, 1]
localdata[1][0:6] = [1, 1, 1, 1, 1]
return localdata
print(example)
newexample = func(example)
print(example)
您是否需要copy.copy(data)
或copy.deepcopy(data)
) 或 data.copy( data.copy()
取决于您对 input 的了解。
另请注意,您的原始代码不会将其return
用于任何事情......
您需要制作一个副本才能正常工作。 由于example
是一个列表列表,因此您必须使用copy.deepcopy()
或列表推导,如下所示:
example =[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
def func(data):
dataCopy = [sublist.copy() for sublist in data]
dataCopy[0][0:6] = [1, 1, 1, 1, 1]
dataCopy[1][0:6] = [1, 1, 1, 1, 1]
return dataCopy
print(example) # all 0's
func(example)
print(example) # still all 0's
print(func(example)) # all 1's
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.