Skip to main content
 首页 » 编程设计

python之在 python 中重构生成器的第一次迭代

2025年05月04日13leader

我想知道是否有办法重构以下代码

 first_run = True 
 for i in gen: 
        if first_run: 
            last_head = i[1] 
            last_tail = i[2] 
            last_chrom = i[0] 
            first_run = False 
        else: 
            func(i[1], last_head) 
            func(i[1], last_tail) 
            last_head = i[1] 
            last_tail = i[2] 
            last_chrom = i[0] 

请您参考如下方法:

循环的要点似乎是对可迭代对象的成对连续元素执行一些操作。所以我会查看函数 pairwise,其定义在 itertools module documentation 中给出。 :

def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = tee(iterable) 
    next(b, None) 
    return izip(a, b) 

请注意,这不是一个实际的 itertools 函数,您必须将实现复制并粘贴到您的代码中。不管怎样,有了这个函数,你的循环可以像这样实现:

for a, b in pairwise(gen): 
    func(b[1], a[1]) 
    func(b[1], a[2])