简体   繁体   English

在Python中重构循环的方法?

[英]Method to refactor the loop in Python?

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 . 这可以通过发电机功能实现。

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

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: 你可以迭代gen()生成的项目,虽然没有构建的“项目列表” - 而是按需构建它:

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

This also means that, if you exit the loop early, the gen() method will be aborted (with an exception). 这也意味着,如果你提前退出循环, gen()方法将被中止(有一个例外)。 Take a look at corutines to understand how this is implemented. 看看corutines ,了解它是如何实现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM