Iterate over pairs in a list (circular fashion) in Python

前端 未结 13 1963
醉酒成梦
醉酒成梦 2020-12-01 01:14

The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).

I\'ve thought about two unpyth

13条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 01:57

    I'd do it like this (mostly because I can read this):

    class Pairs(object):
        def __init__(self, start):
            self.i = start
        def next(self):
            p, p1 = self.i, self.i + 1
            self.i = p1
            return p, p1
        def __iter__(self):
            return self
    
    if __name__ == "__main__":
        x = Pairs(0)
        y = 1
        while y < 20:
            print x.next()
            y += 1
    

    gives:

    (0, 1)
    (1, 2)
    (2, 3)
    (3, 4)
    (4, 5)
    (5, 6)
    (6, 7)
    (7, 8)
    (8, 9)
    

提交回复
热议问题