简体   繁体   English

在函数内附加列表

[英]Appending a list inside a function

I am still a bit confused about how arguments are passed in python. 我仍然对如何在python中传递参数感到困惑。 I thought non-primitive types are passed by reference, but why does the following code not print [1] then? 我认为非原始类型是通过引用传递的,但是为什么下面的代码不能打印[1]呢?

def listTest(L):
    L = L + [1]


def main:
    l = []
    listTest(l)

    print l #prints []

and how could I make it work. 以及如何使它起作用。 I guess I need to pass "a pointer to L" by reference 我想我需要通过引用传递“指向L的指针”

In listTest() you are rebinding L to a new list object; listTest()您将L 重新绑定到新的list对象; L + [1] creates a new object that you then assign to L . L + [1]创建一个新对象,然后将其分配给L This leaves the original list object that L referenced before untouched. 这使L引用之前的原始list对象保持不变。

You need to manipulate the list object referenced by L directly by calling methods on it, such as list.append() : 您需要直接通过调用L所引用的方法来操纵L引用的list对象,例如list.append()

def listTest(L):
    L.append(1)

or you could use list.extend() : 或者您可以使用list.extend()

def listTest(L):
    L.extend([1])

or you could use in-place assignment, which gives mutable types the opportunity to alter the object in-place: 或者您可以使用就地分配,这使可变类型有机会就地更改对象:

def listTest(L):
    L += [1]

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

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