append 方法如何在 python 中工作? [英] How does append method work in python?
本文介绍了append 方法如何在 python 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我学习编程语言,有一个测验问题和解决方案是这样的:
I study programming languages and a quiz question and solution was this:
def foo(x):
x.append (3)
x = [8]
return x
x=[1, 5]
y= foo(x)
print x
print y
为什么会这样打印:
[1 5 3 ]
[8]
为什么 x 不等于 8 ??
Why doesn't x equal to 8 ??
推荐答案
另外两个答案很好.我建议您尝试使用 id
来获取地址.
The other two answers are great. I suggest you to try id
to get address.
看下面的例子
def foo(x):
x.append (3)
print "global",id(x)
x = [8]
print "local ",id(x)
return x
x=[1, 5]
print "global",id(x)
y= foo(x)
print "global",id(x)
print x
print y
和输出
global 140646798391920
global 140646798391920
local 140646798392928
global 140646798391920
[1, 5, 3]
[8]
如您所见,变量 x
的地址在您操作它时保持不变,但在您使用 =
时会发生变化.函数内部的变量赋值使变量局部于函数
As you can see, the address of the variable x
remains same when you manipulate it but changes when you use =
. Variable assignment inside a function makes the variable local to the function
这篇关于append 方法如何在 python 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文