记住函数调用之后阵列的价值 [英] Remember Array value after Function call

查看:100
本文介绍了记住函数调用之后阵列的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样写:

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 是刚刚创建的不同该函数循环。

I'm really new to programming, so please explain it really simply, but how do I stop Python from forgetting what c is after the function has ended? I thought I could fix it by defining c before the function, but obviously that c is different to the one created just for the function loop.

在我的例子,我可以明明只是写:

In my example, I could obviously just write:

c = range (5)
def cf(n)

但我试图写程序更像是这样的:

But the program I'm trying to write is more like this:

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中,你可以在阅读功能全局变量,但你不能默认分配给他们。其原因是,每当发现蟒蛇 C = 它会创建一个局部变量。因此,分配给全球的一个,你需要明确指定要分配给全局变量。

In python you can read global variables in functions, but you cant assigned to them by default. the reason is that whenever python finds c = it will create a local variable. Thus to assign to global one, you need explicitly specify that you are assigning to global variable.

因此​​,这将正常工作,例如:

So this will work, e.g.:

c = [1,2,3]

def cf(): 
    print(c) # it prints [1,2,3], it reads global c

然而,这并不如你所期望的:

However, this does not as you would expect:

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一样,您需要:

So to make c be same, you need:

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()

这篇关于记住函数调用之后阵列的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆