简体   繁体   English

Python传递列表作为参数

[英]Python passing list as argument

If i were to run this code: 如果我要运行此代码:

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

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

Why would it return ['yes'] even though i am not directly changing the variable 'example', and how could I modify the code so that 'example' is not effected by the function? 为什么它会返回['yes'],即使我没有直接更改变量'example',我怎么能修改代码以便'example'不受函数的影响?

Everything is a reference in Python. 一切都是Python的参考。 If you wish to avoid that behavior you would have to create a new copy of the original with list() . 如果您希望避免这种行为,则必须使用list()创建原始文件的新副本。 If the list contains more references, you'd need to use deepcopy() 如果列表包含更多引用,则需要使用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)

outputs 输出

['HI']
[]

The easiest way to modify the code will be add the [:] to the function call. 修改代码的最简单方法是将[:]添加到函数调用中。

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



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

"Why would it return ['yes'] " “为什么它会返回['yes']

Because you modified the list, example . 因为您修改了列表, example

"even though i am not directly changing the variable 'example'." “即使我没有直接改变变量'例子'。”

But you are, you provided the object named by the variable example to the function. 但是,您可以将变量example命名的对象提供给函数。 The function modified the object using the object's append method. 该函数使用对象的append方法修改了对象。

As discussed elsewhere on SO, append does not create anything new. 正如在SO的其他地方所讨论的那样, append不会创造任何新东西。 It modifies an object in place. 它修改了一个对象。

See Why does list.append evaluate to false? 请参阅为什么list.append评估为false? , Python append() vs. + operator on lists, why do these give different results? Python追加()与列表中的+运算符,为什么这些会给出不同的结果? , Python lists append return value . Python列出追加返回值

and how could I modify the code so that 'example' is not effected by the function? 以及如何修改代码以使“示例”不受函数影响?

What do you mean by that? 你是什​​么意思? If you don't want example to be updated by the function, don't pass it to the function. 如果您不希望函数更新example ,请不要将其传递给函数。

If you want the function to create a new list, then write the function to create a new list. 如果希望该函数创建新列表,则编写该函数以创建新列表。

Its because you called the function before printing the list. 这是因为您在打印列表之前调用了该函数。 If you print the list then call the function and then print the list again, you would get an empty list followed by the appended version. 如果您打印列表然后调用该函数,然后再次打印列表,您将得到一个空列表,后跟附加的版本。 Its in the order of your code. 它按你的代码顺序排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM