python for循环if语句问题
当我们运行下面的foor循环时,它会多次输出同一对(见下文),尽管keptPairs只包含不同的元组。有人能快速解决这个问题吗python for循环if语句问题,python,for-loop,Python,For Loop,当我们运行下面的foor循环时,它会多次输出同一对(见下文),尽管keptPairs只包含不同的元组。有人能快速解决这个问题吗 processedPairs = [] bestCorrPairs = [] corrCoefs = [] for pair in keptPairs: if pair not in processedPairs: processedPairs.append(pair) bestCorrCoef = 0 targe
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])
输出:
我们只希望处理每一对。在第一个for循环之后打印对实际上只打印一次,但是,输出结果似乎这些对已经处理了多次。
谢谢大家! 我认为是因为你没有重置你附加的两个变量(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
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