Pairwise circular Python 'for' loop

后端 未结 18 840
执念已碎
执念已碎 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条回答
  •  梦毁少年i
    2020-12-24 10:43

    I like a solution that does not modify the original list and does not copy the list to temporary storage:

    def circular(a_list):
        for index in range(len(a_list) - 1):
            yield a_list[index], a_list[index + 1]
        yield a_list[-1], a_list[0]
    
    for x in circular([1, 2, 3]):
        print x
    

    Output:

    (1, 2)
    (2, 3)
    (3, 1)
    

    I can imagine this being used on some very large in-memory data.

提交回复
热议问题