これは以前の質問のフォローアップです。良い提案を頂けたので、また頑張ってみようと思いました。
from itertools import takewhile
if K is None:
illuminacond = lambda x: x.split(',')[0] != '[Controls]'
else:
illuminacond = lambda x: x.split(',')[0] != '[Controls]' and i < K
af=open('a')
bf=open('b', 'w')
cf=open('c', 'w')
i = 0
if K is None:
for line in takewhile(illuminacond, af):
line_split=line.split(',')
pid=line_split[1][0:3]
out = line_split[1] + ',' + line_split[2] + ',' + line_split[3][1] + line_split[3][3] + ',' \
+ line_split[15] + ',' + line_split[9] + ',' + line_split[10]
if pid!='cnv' and pid!='hCV' and pid!='cnv':
i = i+1
bf.write(out.strip('"')+'\n')
cf.write(line)
else:
for line in takewhile(illuminacond, af):
line_split=line.split(',')
pid=line_split[1][0:3]
out = line_split[1] + ',' + line_split[2] + ',' + line_split[3][1] + line_split[3][3] + ',' \
+ line_split[15] + ',' + line_split[9] + ',' + line_split[10]
if pid!='cnv' and pid!='hCV' and pid!='cnv':
i = i+1
bf.write(out.strip('"')+'\n')
このコードをコンパクトにすることは可能ですか? このように 2 つのループに共通点がある場合、1 つの明白な可能性は、共通のコードを除外することですが、ここでは、えーと。厄介なことに、ここでの唯一の違いは への書き込みc
です。
コードの簡単な要約:K
が None でない場合は、K
の行をループして と の両方にa
書き込みます。それ以外の場合は、 のすべてをループして、に書き込むだけです。b
c
a
b