Note that there are some explanatory texts on larger screens.

plurals
  1. POavoiding code duplication in Python code redux
    primarykey
    data
    text
    <p>This is a followup to an earlier question. I got some good suggestions for that, so I thought I would try my luck again. </p> <pre><code>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 &lt; 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') </code></pre> <p>Is it possible to compactify this code? If I have some stuff in common in two loops like this, one obvious possibility is to just factor out the common code, but here, eww. The annoying thing is that the only difference here is the writing to <code>c</code>.</p> <p>Brief summary of code: If <code>K</code> is not None, then loop over <code>K</code> lines of <code>a</code> and write to both <code>b</code> and <code>c</code>. Otherwise, loop over all of <code>a</code> and just write to <code>b</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload