【发布时间】:2015-02-03 01:14:49
【问题描述】:
如果我这样写:
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。
【问题讨论】:
-
将
global c放在函数顶部,它将使用文件顶层定义的版本,而不是在函数内部创建新变量。 -
global c在cf中使用它 -
我将添加强制不要使用全局,几乎总是有更好的方法。
-
@Patrik333 请注意,尽管
global c是一种有效 解决方案,但它的效果很差。使用return。 -
请注意,您的 if 语句中不需要
is True。对于无论如何都返回布尔值的测试(如 any() 和 all()),它是纯噪声。对于确实有所作为的情况,if blah:几乎肯定是您的意思,而不是if blah is True:。