Sli*_*inc 23 python arguments function list
如果我要运行此代码:
def function(y):
y.append('yes')
return y
example = list()
function(example)
print(example)
Run Code Online (Sandbox Code Playgroud)
为什么它会返回['yes'],即使我没有直接更改变量'example',我怎么能修改代码以便'example'不受函数的影响?
Vin*_*vic 45
一切都是Python的参考.如果您希望避免这种行为,则必须创建原始的新副本list().如果列表包含更多引用,则需要使用deepcopy()
def modify(l):
l.append('HI')
return l
def preserve(l):
t = list(l)
t.append('HI')
return t
example = list()
modify(example)
print(example)
example = list()
preserve(example)
print(example)
Run Code Online (Sandbox Code Playgroud)
输出
['HI']
[]
Run Code Online (Sandbox Code Playgroud)
小智 9
修改代码的最简单方法是将[:]添加到函数调用中.
def function(y):
y.append('yes')
return y
example = list()
function(example[:])
print(example)
Run Code Online (Sandbox Code Playgroud)
"它为什么会回来['yes']"
因为你修改了列表example.
"即使我没有直接改变变量'例子'."
但是,您提供了由变量命名的对象example到函数.该函数使用对象的append方法修改了对象.
正如其他地方所讨论的那样,append并没有创造任何新东西.它修改了一个对象.
请参阅为什么list.append评估为false?,Python追加()与列表中的+运算符,为什么这些会给出不同的结果?,Python列出追加返回值.
以及如何修改代码以使"示例"不受函数影响?
你是什么意思?如果您不想example通过该功能进行更新,请不要将其传递给该功能.
如果希望该函数创建新列表,则编写该函数以创建新列表.
| 归档时间: |
|
| 查看次数: |
80007 次 |
| 最近记录: |