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

前端 未结 13 2005
醉酒成梦
醉酒成梦 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 02:11

    This might be satisfactory:

    def pairs(lst):
        for i in range(1, len(lst)):
            yield lst[i-1], lst[i]
        yield lst[-1], lst[0]
    
    >>> a = list(range(5))
    >>> for a1, a2 in pairs(a):
    ...     print a1, a2
    ...
    0 1
    1 2
    2 3
    3 4
    4 0
    

    If you like this kind of stuff, look at python articles on wordaligned.org. The author has a special love of generators in python.

提交回复
热议问题