简体   繁体   English

我的Python for循环有什么问题?

[英]What's wrong with my Python for loop?

I have two files open, EQE_data and Refl_data. 我打开了两个文件,EQE_data和Refl_data。 I want to take each line of EQE_data, which will have eight tab-delimited columns, and find the line in Refl_data which corresponds to it, then do the data analysis and write the results to output. 我想获取每行EQE_data,它将有八个制表符分隔的列,并在Refl_data中找到与之对应的行,然后进行数据分析并将结果写入输出。 So for each line in EQE_data, I need to search the entire Refl_data until I find the right one. 因此,对于EQE_data中的每一行,我需要搜索整个Refl_data,直到找到正确的一行。 This code is successful the first time, but it is outputting the same results for the Refl_data every subsequent time. 此代码第一次成功,但每次后续输出Refl_data的相同结果。 Ie, I get the correct columns for Wav1 and QE, but it seems to only be executing the nested for loop once, so I get the same R, Abs, IQE, which is correct for the first row, but incorrect thereafter. 即,我得到Wav1和QE的正确列,但它似乎只执行嵌套for循环一次,所以我得到相同的R,Abs,IQE,这对于第一行是正确的,但此后不正确。

for line in EQE_data:
    try:
        EQE = line.split("\t")
        Wav1, v2, v3, QE, v5, v6, v7, v8 = EQE
        for line in Refl_data:
            Refl = line.split("\t")
            Wav2, R = Refl
            if float(Wav2) == float(Wav1):
                Abs = 1 - (float(R) / 100)
                IQE = float(QE) / Abs
        output.write("%d\t%f\t%f\t%f\t%f\n" % (int(float(Wav1)), float(QE), float(R) / 100, Abs, IQE))
    except:
        pass

If Refl_data is a file, you need to put the read pointer back to the beginning in each loop (using Refl_data.seek(0) ), or just re-open the file. 如果Refl_data是一个文件,则需要将读指针放回每个循环的开头(使用Refl_data.seek(0) ),或者只是重新打开文件。

Alternatively, read all of Refl_data into a list first and loop over that list instead. 另外,阅读所有的Refl_data到列表第一和遍历该列表来代替。

Further advice: use the csv module for tab-separated data, and don't ever use blank try: - except: ; 进一步的建议:使用csv模块进行制表符分隔数据,不要使用空白try: - except: ; always only catch specific exceptions. 总是只捕捉特定的例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM