Pairwise circular Python 'for' loop

后端 未结 18 871
执念已碎
执念已碎 2020-12-24 10:24

Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first.

So for instance, if I have the list

18条回答
  •  醉酒成梦
    2020-12-24 10:57

    This is my solution, and it looks Pythonic enough to me:

    l = [1,2,3]
    
    for n,v in enumerate(l):
        try:
            print(v,l[n+1])
        except IndexError:
            print(v,l[0])
    

    prints:

    1 2
    2 3
    3 1
    

    The generator function version:

    def f(iterable):
        for n,v in enumerate(iterable):
            try:
                yield(v,iterable[n+1])
            except IndexError:
                yield(v,iterable[0])
    
    >>> list(f([1,2,3]))
    [(1, 2), (2, 3), (3, 1)]
    

提交回复
热议问题