【发布时间】:2011-05-03 19:37:50
【问题描述】:
这是对先前问题的后续处理。我得到了一些很好的建议,所以我想我会再试试运气。
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')
是否可以压缩此代码?如果我在这样的两个循环中有一些共同点,
一种明显的可能性是只考虑通用代码,但在这里,eww。
烦人的是这里唯一的区别是写信给c。
代码简要总结:如果K 不是None,则遍历a 的K 行并写入b 和c。否则,遍历所有a,然后写信给b。
【问题讨论】:
标签: python code-duplication control-flow