名称错误…未定义全局

2024-10-02 12:23:55 发布

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

我对这个代码有问题。虽然名字错误似乎很普遍,但我无法通过搜索找到解决方法。这是密码。。。在

def fmp_sel():
    with open ('MonPlotDb.csv', 'rU') as csvfile: 
            next(csvfile, None)
            fmpList = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
            for item in enumerate(fmpList):
                    print "[%d] %s" % (item)
    while True:
        try:
            in_Sel = raw_input(('''Choose from list or 'q' to quit:'''))                                               
             if in_Sel == 'q':
                print 'Quit?'                                           
                conf = raw_input('Really? (y or n)...')    
                if conf == 'y':                                              
                    print 'Seeya!'                                        
                    break
                else:
                    continue                                                        
             plotOrig = DataPlotLoc[int(in_Sel) + 1]                              
            print 'You selected', plotOrig[1]                
            break
        except (ValueError, IndexError):
            print 'Error: Try again'

回溯。。。。在

^{pr2}$

此函数是从main()调用的,但我不明白为什么“DataPlotLoc”是一个全局名称,因为它在这个函数中。不管怎样,我想我错过了一句话来定义它,但是我不知道如何和在哪里。我很想得到帮助。在

编辑: 为了增加更多的信息,DataPlotLoc是插入代码时列表的名称,即DataPlotLoc=[['a','b','c',…..]]并且它起作用了。线 plotOrig=DataPlotLoc[int(in_Sel)+1]引用此列表,但显然它现在被读入csv.reader所以现在我不确定如何分配这个变量。 我假设在确认用户是否输入'q'后,我仍然需要它接受一个整数,+1将添加到输入的数字中,以便它与从列表中选择的相应行项目的正确索引号对齐。 抱歉,如果这有点混乱,但我自己也有点困惑。。。在


Tags: orcsvcsvfile代码in列表inputraw
2条回答

好吧,正如错误消息所说,您在定义它之前使用了DataPlotLoc。如果你搜索你的代码,你会发现它从来没有被定义过。如果你不知道你想说什么,我就不能回答更多的问题了。在

Python假设您指的是该名称的全局变量,因为您从未给它分配任何东西,这会使它成为局部变量。在

Python之所以说global name ... not defined,是因为它在函数体中没有看到对DataPlotLoc的任何赋值,所以它假设它必须是一个全局变量,但在那里找不到它。(见下面阿巴内特的评论)

根据代码判断,我想您希望DataPlotLoc包含从MonPlotDb.csv提取的信息,在这种情况下,您需要做两件事:

(A)初始化DataPlotLoc

def fmp_sel():
    DataPlotLoc = []  # <        -!!!!
    with open ('MonPlotDb.csv', 'rU') as csvfile:

(B)在循环和打印选项时,将值附加到DataPlotLoc。在

^{pr2}$

我不知道为什么要在plotOrig = DataPlotLoc[int(in_Sel) + 1]的行中添加一个,我认为您可以将csv.reader行简化为下面的csv.reader(csvfile)(我认为带逗号的excel是默认行为)

编辑:要从CSV的每一行提取一列,请将B部分中的代码改为如下所示:

    next(csvfile, None)
    fmpList = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
    for item in enumerate(fmpList):
        i, data = item  # enumerate returns tuples of the form (i, data)
        vals = (i, data[1])  # <  - put in the proper index of the column
        DataPlotLoc.append(vals)
        print "[%d] %s" % vals  # < - assuming  you want to change the print as well

相关问题 更多 >

    热门问题