python重复代码_避免Python代码redux中的代码重复

这是对早期问题的后续跟进.我得到了一些很好的建议,所以我想我会再试一次运气.

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,则循环遍历K行的a行并写入b和c.否则,遍历所有a并只写入b.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值