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

前端 未结 13 2006
醉酒成梦
醉酒成梦 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:59

    This infinitely cycles, for good or ill, but is algorithmically very clear.

    from itertools import tee, cycle
    
    def nextn(iterable,n=2):
        ''' generator that yields a tuple of the next n items in iterable.
        This generator cycles infinitely '''
        cycled = cycle(iterable)
        gens = tee(cycled,n)
    
        # advance the iterators, this is O(n^2)
        for (ii,g) in zip(xrange(n),gens):
            for jj in xrange(ii):
                gens[ii].next()
    
        while True:
            yield tuple([x.next() for x in gens])
    
    
    def test():
        data = ((range(10),2),
            (range(5),3),
            (list("abcdef"),4),)
        for (iterable, n) in data:
            gen = nextn(iterable,n)
            for j in range(len(iterable)+n):
                print gen.next()            
    
    
    test()
    

    gives:

    (0, 1)
    (1, 2)
    (2, 3)
    (3, 4)
    (4, 5)
    (5, 6)
    (6, 7)
    (7, 8)
    (8, 9)
    (9, 0)
    (0, 1)
    (1, 2)
    (0, 1, 2)
    (1, 2, 3)
    (2, 3, 4)
    (3, 4, 0)
    (4, 0, 1)
    (0, 1, 2)
    (1, 2, 3)
    (2, 3, 4)
    ('a', 'b', 'c', 'd')
    ('b', 'c', 'd', 'e')
    ('c', 'd', 'e', 'f')
    ('d', 'e', 'f', 'a')
    ('e', 'f', 'a', 'b')
    ('f', 'a', 'b', 'c')
    ('a', 'b', 'c', 'd')
    ('b', 'c', 'd', 'e')
    ('c', 'd', 'e', 'f')
    ('d', 'e', 'f', 'a')
    

提交回复
热议问题