如何将列表作为参数传递?

时间:2016-12-13 12:32:41

标签: python list parameters

使用以下代码

def test(n): 
    n=n*2 
    print("inside test",n) 

n=[9] 
print("before the call", n) 
test(n) 
print("after the call", n) 

输出是:

before the call [9]
inside test [9, 9]
after the call [9]

我认为函数中列表参数的传递是通过引用和修改调用参数来完成的。这里的情况并非如此:令人惊讶。我在期待:

before the call [9]
inside test [9, 9]
after the call [9, 9]

如果我使用append方法而不是n=n*2,则效果正常。 请问有人澄清这一点吗?

4 个答案:

答案 0 :(得分:2)

它是关于可变或不可变的类型和值或引用参数。 Python传递“引用”但不是真的(这里有详细信息:https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/

>>> def update_list(the_list):
    print('got', the_list)
    the_list.append('four')
    print('changed to', the_list)

>>> toto = ["one"]
>>> update_list(toto)
got ['one']
changed to ['one', 'four']
>>> print(toto)
['one', 'four']


>>> def new_list(the_list):
    print('got', the_list)
    the_list = the_list + ["four"]
    print('changed to', the_list)

>>> toto = ["one"]
>>> new_list(toto)
got ['one']
changed to ['one', 'four']
>>> print(toto)
['one']

Python文档: https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference

类似的问题: How do I pass a variable by reference?

答案 1 :(得分:1)

此行n = n*2会在n函数中创建一个新的局部变量test(),这就是为什么外部变量没有更改的原因。看看这些例子:

>>> def test(n):
...     print(id(n))
...     n = n*2
...     print(id(n))
...     print("inside test", n)
...
>>> def test2(n):
...     print(id(n))
...     n.append(2)
...     print(id(n))
...     print("inside test2", n)
...
>>> n = [9]
>>> id(n)
49744472
>>>
>>> test(n)
49744472
49744752
('inside test', [9, 9])
>>>
>>> test2(n)
49744472
49744472
('inside test2', [9, 2])

test()内,我们有两个不同的ID:参数 49744472 n本地变量<{1}} / strong> 49744752。在n函数中打印相同的ID,这意味着在函数内部更改了相同的 param test2()

答案 2 :(得分:0)

在python中,通常将引用传递给函数的参数引用为值/传递引用是很困惑的。

N = [9]

上述语句将n绑定到包含值为9的单个元素的List对象。(在这种情况下为[9])

当n = n * 2时 这将创建一个新的List并绑定到一个变量,该变量是函数范围的本地变量。

答案 3 :(得分:0)

在n = n * 2中,在测试函数内部创建一个局部变量,返回n并将其赋值给n,结果为

def test(n): 
    n=n*2 
    print("inside test",n) 
    return n

n=[9] 
print("before the call", n) 
n = test(n) 
print("after the call", n) 

输出:

('before the call', [9])
('inside test', [9, 9])
('after the call', [9, 9])