bio*_*ard 15 python loops nested break
我有两个制表符分隔的文件,我需要测试第一个文件中的每一行与另一个文件中的所有行.例如,
文件1:
row1 c1 36 345 A
row2 c3 36 9949 B
row3 c4 36 858 C
Run Code Online (Sandbox Code Playgroud)
文件2:
row1 c1 3455 3800
row2 c3 6784 7843
row3 c3 10564 99302
row4 c5 1405 1563
Run Code Online (Sandbox Code Playgroud)
假设我想输出(file1)中的所有行,其中file1的col [3]小于file2的任何(不是每个)col [2],因为col [1]是相同的.
预期产量:
row1 c1 36 345 A
row2 c3 36 9949 B
Run Code Online (Sandbox Code Playgroud)
由于我在Ubuntu工作,我希望输入命令看起来像这样:
python code.py [file1] [file2] > [output]
我写了以下代码:
import sys
filename1 = sys.argv[1]
filename2 = sys.argv[2]
file1 = open(filename1, 'r')
file2 = open(filename2, 'r')
done = False
for x in file1.readlines():
col = x.strip().split()
for y in file2.readlines():
col2 = y.strip().split()
if col[1] == col2[1] and col[3] < col2[2]:
done = True
break
else: continue
print x
Run Code Online (Sandbox Code Playgroud)
但是,输出看起来像这样:
row2 c3 36 9949 B
Run Code Online (Sandbox Code Playgroud)
这对于较大的数据集来说是显而易见的,但基本上我总是只获得嵌套循环中的条件为真的最后一行.我怀疑"休息"让我脱离了两个循环.我想知道(1)如何打破只有一个for循环,以及(2)如果这是我遇到的唯一问题.
NPE*_*NPE 24
break并continue应用于最内层的循环.
问题是您只打开第二个文件一次,因此它只读一次.for y in file2.readlines():第二次执行时,file2.readlines()返回一个空的iterable.
要么移动file2 = open(filename2, 'r')到外部循环,要么使用seek()倒带到开头file2.