Python更改参数列表

2024-04-18 19:15:05 发布

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

我想更改作为参数给定的列表项。 例如

def method(list) :
    list = [1,2,3]

我希望任何列表作为参数更改为[1,2,3]。 所以我得到了这样的结果:

>>> a =[4,5,6]
>>> method(a)
>>> a
[1,2,3]

Tags: 列表参数defmethodlist
3条回答

使用列表切片:

 def method(l):
     l[:]=[1,2,3]

使用以下函数。你知道吗

def method(lst) :
    list_ = [1,2,3]
    return list_

a = [4,1,2]

a = method(a)

首先,不要使用list作为您自己的变量,因为这会屏蔽内置函数list()。你知道吗

list是通过引用传递的,但是如果您在函数的局部作用域中重新为引用赋值,那么引用只会指向新对象。相反,return创建新对象,然后保存对它的引用。你知道吗

>>> def method(lst):
...     return [1, 2, 3]
...
>>> a = [4, 5, 6]
>>> a = method(a)
>>> a
[1, 2, 3]

相关问题 更多 >