For example, there’re two similar codes:
The first one is:
for chrom in bins:
for a_bin in bins[chrom]:
for pos in a_bin:
pos = pos+100
The second one is:
for chrom in bins:
for a_bin in bins[chrom]:
for pos in a_bin:
if chrom=="chr1":
pos = pos*100
I was wondering that whether there’s a way to refactor the loop so that I don’t need to repeat writing code with the same structure..
Anyone has ideas about this?
This can be achieved with a generator function.
You can iterate through the items generated by
gen(), though there is no “list of item” that is built — rather, it is constructed on demand:This also means that, if you exit the loop early, the
gen()method will be aborted (with an exception). Take a look at corutines to understand how this is implemented.