Pairwise circular Python 'for' loop

后端 未结 18 865
执念已碎
执念已碎 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:52

    this seems like combinations would do the job.

    from itertools import combinations
    x=combinations([1,2,3],2)
    

    this would yield a generator. this can then be iterated over as such

    for i in x:
      print i
    

    the results would look something like

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

提交回复
热议问题