Python传递列表为argumen

2024-05-17 06:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我要运行此代码:

def function(y):
    y.append('yes')
    return y

example = list()
function(example)
print(example)

即使我没有直接更改变量“example”,它为什么会返回[“yes”];我如何修改代码以使“example”不受函数的影响?


Tags: 函数代码returnexampledeffunctionlistyes
3条回答

修改代码的最简单方法是将[:]添加到函数调用中。

def function(y):
    y.append('yes')
    return y



example = list()
function(example[:])
print(example)

一切都是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)

输出

['HI']
[]

“为什么会返回['yes']

因为你修改了列表,example

“即使我没有直接更改变量‘example’。”

但实际上,您为函数提供了由变量example命名的对象。函数使用对象的append方法修改了对象。

正如其他地方所讨论的,append不会产生任何新的东西。它在适当的位置修改一个对象。

Why does list.append evaluate to false?Python append() vs. + operator on lists, why do these give different results?Python lists append return value

如何修改代码,使“example”不受函数的影响?

你说那是什么意思?如果不希望函数更新example,请不要将其传递给函数。

如果希望函数创建新列表,请编写函数以创建新列表。

相关问题 更多 >