gpt4 book ai didi

python - 为什么 python 中的列表操作在函数范围之外运行?

转载 作者:太空狗 更新时间:2023-10-29 21:50:03 25 4
gpt4 key购买 nike

<分区>

在下面的 python 代码中,变量 number 被传递给函数 addone,并在本地副本上进行操作。 number 的值保持不变。

def addone(num):
num = num + 1
print "function: added 1, now %d" % num

number = 5
print "Before:", number
addone(number)
print "After:", number

输出:

Before: 5
function: added 1, now 6
After: 5

但是,行为似乎与弹出、追加等列表操作不同。这让我有些困惑。所有列表操作都在全局范围内运作吗?如果是这样,背后有什么特别的原因吗?

def pop_first(stuff):
popped = stuff.pop(0)
print "function: '%s' was popped!" % popped

words = ["A", "list", "of", "words"]
print "Before:", words
pop_first(words)
print "After:", words

输出:

Before: ['A', 'list', 'of', 'words']
function: 'A' was popped!
After: ['list', 'of', 'words']

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com