python for循环if语句问题

时间:2018-05-01 15:01:24

标签: python for-loop

当我们运行以下foor循环时,它会多次输出相同的对(参见下面的内容),尽管keepPairs只包含不同的元组。有没有人快速解决这个问题?

processedPairs = []
bestCorrPairs = []
corrCoefs = []
for pair in keptPairs:
    if pair not in processedPairs:
        processedPairs.append(pair)
        bestCorrCoef = 0
        targetx = pair[0]
        t_y = []
        for p in keptPairs:
            if targetx in p:
                if (p[0]!=targetx): t_y.append(p[0])
                else: t_y.append(p[1])
            else: continue
        for targety in t_y:
            corr = calcCorr(final_t,targetx, targety)
            if (np.abs(corr) > np.abs(bestCorrCoef) and not (corr==0 or corr==1)):
                bestCorrCoef = corr
                bestPair = tuple([targetx, targety])
            else: continue

        bestCorrPairs.append(bestPair)
        corrCoefs.append(bestCorrCoef)
    else: continue

for i in range(0,len(bestCorrPairs)):
    print(bestCorrPairs[i], ': ', corrCoefs[i])

出:

('9.4', '15.4') :  0.9906385237419475
('9.4', '15.4') :  0.9906385237419475
('9.4', '15.4') :  0.9906385237419475
('9.4', '15.4') :  0.9906385237419475
('9.4', '15.4') :  0.9906385237419475
('9.4', '15.4') :  0.9906385237419475
('9.4', '15.4') :  0.9906385237419475
('3.1', '15.1') :  -0.9815967899407816
('3.1', '15.1') :  -0.9815967899407816
('17.8', '6.2') :  -0.9982604771744984
('6.2', '17.8') :  -0.9982604771744984
('10.c', '7.2') :  -0.8082515774139288
('17.3', '15.1') :  0.9810874111013809
etc.

我们只想处理每一对。在第一个for循环之后打印对实际上只打印一次,但是,输出似乎已经多次处理这些对。 谢谢!

1 个答案:

答案 0 :(得分:0)

我认为是因为你没有重置你追加的两个变量(bestPair,bestCorrCoef)...尝试在启动for循环时重置两个变量,或者你可以这样做:

for targety in t_y:
        corr = calcCorr(final_t,targetx, targety)
        if (np.abs(corr) > np.abs(bestCorrCoef) and not (corr==0 or corr==1)):
            bestCorrCoef = corr
            bestPair = tuple([targetx, targety])

            bestCorrPairs.append(bestPair)
            corrCoefs.append(bestCorrCoef)
        else: continue