函数中的Python访问全局列表

2024-10-01 09:33:38 发布

您现在位置: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

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

^{pr2}$

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

[1, 2, 3, 4]

有人能帮我找到解决办法吗?在

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

编辑: 谢谢马蒂恩·皮特斯的建议。 原始错误为

UnboundLocalError: local variable 'globlist' referenced before assignment

Tags: fromlendef错误anotherfunctionthis建议
3条回答

您可以:

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

不过,把它传入并修改它可能会更像Python。在

在函数cmplist中,对象“globlist”不被认为来自全局范围。Python解释器将其视为局部变量;在函数cmplist中找不到该变量的定义。因此出现了错误。 在函数内部,在第一次使用globlist之前将其声明为“global”。 类似这样的方法会起作用:

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

嗯, 斯瓦南德

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

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

相关问题 更多 >