首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >列表是如何作为参数传递的?

列表是如何作为参数传递的?
EN

Stack Overflow用户
提问于 2016-12-13 12:32:41
回答 4查看 62关注 0票数 0

使用以下代码

代码语言:javascript
复制
def test(n): 
    n=n*2 
    print("inside test",n) 

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

它的输出是:

代码语言:javascript
复制
before the call [9]
inside test [9, 9]
after the call [9]

我认为在函数中传递列表参数是通过引用和修改调用parameters.It的方式进行的,这里的情况不是这样的: passing。我原以为:

代码语言:javascript
复制
before the call [9]
inside test [9, 9]
after the call [9, 9]

如果我使用append方法而不是n=n*2,效果是可以的。有人能澄清这一点吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-12-13 12:51:31

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

代码语言:javascript
复制
>>> 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?

票数 2
EN

Stack Overflow用户

发布于 2016-12-13 12:42:23

这一行n = n*2在您的test()函数中创建了一个新的局部变量n,这就是为什么外部变量不被更改的原因。看看下面的例子:

代码语言:javascript
复制
>>> 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()中,我们有两个不同的ids:49744472用于param n49744752用于(局部变量 n )。在test2()函数中,打印相同的id,这意味着在函数中更改相同的param n

票数 1
EN

Stack Overflow用户

发布于 2016-12-13 12:45:19

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

n=9

上述语句将n绑定到包含值为9的单个元素的List对象(本例中为9)。

当n=n*2时,这将创建一个新的列表并绑定到一个变量,该变量是函数作用域的局部变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41121246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档