如果我这样写:
c = []
def cf(n):
c = range (5)
print c
if any((i>3) for i in c) is True:
print 'hello'
cf(1)
print c
然后我得到:
[1, 2, 3, 4]
hello
[]
我真的是编程新手,所以请简单地解释一下,但是如何阻止 Python 在函数结束后忘记 c
是什么?我以为我可以通过在函数之前定义 c
来修复它,但显然 c
与仅为函数循环创建的那个不同。
在我的示例中,我显然可以只写:
c = range (5)
def cf(n)
但我尝试编写的程序更像这样:
b = [blah]
c = []
def cf(n):
c = [transformation of b]
if (blah) is True:
'loop' cf
else:
cf(1)
g = [transformation of c that produces errors if c is empty or if c = b]
所以我不能在函数外定义c
。
最佳答案
在 python 中,你可以读取函数中的全局变量,但默认情况下你不能分配给它们。原因是每当 python 找到 c =
时,它都会创建一个局部变量。因此,要分配给全局变量,您需要明确指定要分配给全局变量。
所以这会起作用,例如:
c = [1,2,3]
def cf():
print(c) # it prints [1,2,3], it reads global c
但是,这并不像您期望的那样:
c = [1,2,3]
def cf():
c = 1 # c is local here.
print(c) # it prints 1
cf()
print(c) # it prints [1,2,3], as its value not changed inside cf()
所以要使 c 相同,您需要:
c = [1,2,3]
def cf():
global c
c = 1 # c is global here. it overwrites [1,2,3]
print(c) # prints 1
cf()
print(c) # prints 1. c value was changed inside cf()
关于python - 函数调用后记住数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27306212/