分配前已引用局部变量“ temp”

时间:2018-09-20 11:19:28

标签: python

我正在尝试在python中调用以下函数。每当我调用以下函数

TFIDF_score = compute_TFIDF(TF_score, IDF_score)

我收到一个错误[ local variable 'temp' referenced before assignment ]

下面是参考代码

def compute_TFIDF(TF_score,IDF_score):
    TFIDF_score=[]
    for j in IDF_score:
        for i in TF_score:
            if j['key'] == i['key'] and j['doc_id'] == i['doc_id']:
                temp= {'doc_id': j['doc_id'],
                       'TFIDF_score': j['IDF_score']*i['TF_score'],
                       'key': i['key']}    
            TFIDF_score.append(temp)

    return TFIDF_score

任何解决方案,因为我已经分配了temp变量,然后再传递它。

1 个答案:

答案 0 :(得分:0)

如果if子句中的测试在第一次迭代中为假,则未定义temp,但是您仍然尝试将其无条件地附加到TDIF_score。另外,如果测试在第一个迭代中为true(在这种情况下您没有NameError),则在下一个迭代中测试为false时,您将再次附加上一个迭代中的temp

很显然,您希望缩进TFIDF_score.append(temp)行,使其位于if块内:

for j in IDF_score:
    for i in TF_score:
        if j['key'] == i['key'] and j['doc_id'] == i['doc_id']:
            temp= {'doc_id': j['doc_id'],
                   'TFIDF_score': j['IDF_score']*i['TF_score'],
                   'key': i['key']}    
            TFIDF_score.append(temp)