Python - 在函数中访问全局列表

时间:2017-06-23 06:42:35

标签: python

我是Python的新手,在此之前,我正在使用C。

def cmplist(list): #Actually this function calls from another function
    if (len(list) > len(globlist)):
        globlist = list[:] #copy all element of list to globlist

# main
globlist = [1, 2, 3]
lst = [1, 2, 3, 4]
cmplist(lst)
print globlist

当我执行此代码时,它显示以下错误

    if (len(list) > len(globlist)):
NameError: global name 'globlist' is not defined

我想从函数访问和修改globlist而不将其作为参数传递。在这种情况下,输出应为

[1, 2, 3, 4]

有人可以帮我找到解决方案吗?

欢迎任何建议和更正。 提前谢谢。

修改 感谢Martijn Pieters的建议。 原始错误是

UnboundLocalError: local variable 'globlist' referenced before assignment

3 个答案:

答案 0 :(得分:4)

你可以这样做:

def cmplist(list): #Actually this function calls from another function
    global globlist
    if (len(list) > len(globlist)):
        globlist = list[:] #copy all element of list to globlist

传入它可能会更加Pythonic并以这种方式修改它。

答案 1 :(得分:0)

您需要在函数中将其声明为全局:

def cmplist(list): #Actually this function calls from another function
    global globlist
    if len(list) > len(globlist):
        globlist = list[:] #copy all element of list to globlist

# main
globlist = [1, 2, 3]
lst = [1, 2, 3, 4]
cmplist(lst)
print globlist

答案 2 :(得分:0)

内部功能cmplist,object' globlist'不被视为来自全球范围。 Python解释器将其视为局部变量;在函数cmplist中找不到它的定义。因此错误。 在函数内部声明globlist为' global'在它第一次使用之前。 像这样的东西会起作用:

def cmplist(list):
     global globlist
     ... # Further references to globlist

HTH, Swanand