Python返回未定义的全局变量

2024-04-25 12:20:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个方法,在里面我用python扫描一个excel文件,在另一个方法中,我想检查列表中的一个条目,在这个列表中,我用第一种方法从excel表中提取数据,如下所示:

def first():
    nodes_sh = xlrd.open_workbook(file_location)
    sh_method = nodes_sh.sheet_by_index(0)
    global node_data_inter
    node_data_inter = [[sh_method.cell_value(rr, co) for co in range(sh_method.ncols)] for rr in range(sh_method.nrows)] #O(rows*cols) # A loop to get all the data in the excel sheet of "Nodes Co-ordinates"
    global node_positions_ascending_inter
    node_positions_ascending_inter = dc.deepcopy(node_data_inter) #O(rows*cols)
    for rowss in range(len(node_positions_ascending_inter)): #O(rows)
        del (node_positions_ascending_inter[rowss][0:3])
        del (node_positions_ascending_inter[rowss][2])


def using_from_first_method():
    global node_positions_ascending_inter
    if node_positions_ascending_inter[0][0] == 1.25:
        print "Yes"

当我键入using_from_first_method()时,输出一条错误消息

^{pr2}$

为什么我已经将node_positions_ascending_inter定义为一个全局变量而输出它?在


Tags: 方法innodefordatashrangeexcel
1条回答
网友
1楼 · 发布于 2024-04-25 12:20:58

您需要declare node_positions_ascending_inter作为using_from_first_method函数中的全局变量。我得到了下面的代码(简化)运行良好。

def first():
    global node_positions_ascending_inter
    node_positions_ascending_inter = [1.25, 1.5, 1.3, 1.45]

def using_from_first_method():
    global node_positions_ascending_inter
    if node_positions_ascending_inter[0] == 1.25:
        print("Yes")

first()
using_from_first_method()

如果您仍然有问题,可能问题在于数组的填充。在第二个方法尝试访问前,您确定第一个方法已被调用并成功创建了全局?另外,请参阅有关globalshere的文档。

相关问题 更多 >