Python loop refactoring method?

For example, there are two similar codes:

First:

for chrom in bins: for a_bin in bins[chrom]: for pos in a_bin: pos = pos+100 

Second:

  for chrom in bins: for a_bin in bins[chrom]: for pos in a_bin: if chrom=="chr1": pos = pos*100 

I was wondering if there is a way to reorganize the loop so that I do not need to write code with the same structure.

Anyone have any ideas on this?

+4
source share
1 answer

This can be achieved using the function.

 def gen(): for chrom in bins: for a_bin in bins[chrom]: for pos in a_bin: yield pos 

You can iterate over the elements generated using gen() , although there is no "list of elements" that is built, but built on demand:

 for pos in gen(): pass # add loop code here 

It also means that if you exit the loop earlier, the gen() method will be aborted (with an exception). See corutines to see how this is implemented.

+3
source

Source: https://habr.com/ru/post/1442924/


All Articles