制作全球可用列表

时间:2018-04-03 13:57:07

标签: python

我想访问一个列表,该列表是来自不同python函数的字段。有关详细信息,请参阅以下代码

abc = []
name = "apple,orange"
def foo(name):
   abc = name.split(',')
   print abc

foo(name)
print abc
print name

输出如下。

  

['apple','orange']

     

[]

     

苹果,桔子

因为我是python的新手所以有人可以解释为什么第7行(print abc)没有给出结果为''apple','orange']?

如果我需要在第7行(['apple','orange'])填写列表,我该怎么办?

3 个答案:

答案 0 :(得分:2)

abc = []
name = "apple,orange"
def foo(name):
   global abc # do this
   abc = name.split(',')
   print abc

foo(name)
print abc
print name

答案 1 :(得分:2)

虽然其他答案建议使用global abc,但一般认为使用全局变量是不好的做法。见why are global variables evil?

更好的方法是return变量:

name = "apple,orange"
def foo(name):
   abc = name.split(',')
   return abc

abc = foo(name)
print abc
print name

答案 2 :(得分:0)

函数中的abc与第一行的abc不同,因为def foo中的abc是局部变量,如果要引用上面声明的abc,则必须使用global abc。