python列表控制错误:未定义全局名称

2024-10-01 00:33:58 发布

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

我遇到了一个奇怪的问题。错误消息是: 未定义全局名称“id2tag”。 我读过这篇文章Accessing class variables from a list comprehension in the class definition。但显然id2tag不是一个类变量。代码如下所示。在

class evaluater:
    def evaluate_topk(self, ground_truth_dict, predicted_dict, setting_name, setting, data,
                      eval_root_dir = './', file_name = 'result',k = 5,output_entry = 100 ):
        #this part of code is not relevant
        recall = {}
        for key, ground_truth in ground_truth_dict.items():
            recall[key] = recall_at_k(ground_truth, predicted_dict[key])

        mean_recall = np.mean([value for key,value in recall.items()])

        filepath = eval_root_dir + file_name
        if not os.path.exists(os.path.dirname(filepath)):
            os.makedirs(os.path.dirname(filepath))        

        #HERE IS WHERE id2tag DEFINED
        id2tag = {row[0]:row[1] for row in data[config.TYPE_TAG] }
        with open( filepath , 'a' ) as file:
            for itemid in sorted(ground_truth_dict.keys())[1:100]:
                file.write(str(itemid) + '\n')

                file.write('gnd:'+str([id2tag[id] for id in ground_truth_dict[itemid]] ) + '\n')
                file.write('prt' + str([ id2tag[id] for id in predicted_dict[itemid]]) + '\n' )
                #if i use the below code instead, then would be fine
                #gnd_tags = []
                #prt_tags = []
                #for id in ground_truth_dict[itemid]:
                #    gnd_tags.append(id2tag[id])
                #    
                #for id in predicted_dict[itemid]:
                #    prt_tags.append(id2tag[id])
                #    
                #file.write('gnd:'+str( gnd_tags ) + '\n')
                #file.write('prt' + str(prt_tags) + '\n' )

        return mean_recall

Tags: inidfortagsdictfilewriteprt
2条回答

这是个奇怪的问题。在中调试类函数的命名空间时遇到了它py.测试在pdb中。pdb之外没有错误。在

(Pdb) lines=["oneline",2,3,4,5]
(Pdb) ip_dict = dict( ( lines[i], lines[i+1] ) for i in range(0,len(lines),2) )
*** NameError: global name 'lines' is not defined
(Pdb) for i in range(0,len(lines),2): print "%d=%s" % (i,lines[i])
0=oneline
2=3
4=5

(Pdb) self
<Docker-sanity_regression.SANITY testMethod=test_SANITY_002_####_container>

为了简化问题,这里有一个例子。在

^{pr2}$

这对于Python2.4很好。和Python2.7。 在类func中嵌入dict集:

class Test:
    def __init__(self):
        print "init"
        self.ip_dict = {}

    def setDict(self):
        lines=["oneline",2,3,4,5]
        self.ip_dict = dict( ( lines[i], lines[i+1] ) for i in range(0,len(lines),2) )
        print self.ip_dict

foo = Test()
foo.setDict()

这对于python2.4也很适用。和Python2.7。在

因此,我认为在某些版本的python和pdb中存在一个有趣的名称空间问题,用于这种理解。 编辑:是的。pdb的已知问题。感谢https://stackoverflow.com/users/396967/kynan的解释。https://bugs.python.org/issue21161Title:列表理解在python3中看不到pdb中的局部变量

复杂的嵌入代码中存在语法错误。我想如果你把一行代码分成三行,你的奇怪问题就会消失:

# Change this line 
id2tag = {row[0]:row[1] for row in data[config.TYPE_TAG]}

# Change to this
id2tag = {}
for row in data[config.TYPE_TAG]:
    id2tag[row[0]] = row[1]

顺便说一句:我建议不要以您的方式使用embedded for x in list_var,这对于其他代码读者来说不太容易阅读和理解。在

相关问题 更多 >