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

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

    I've coded myself the tuple general versions, I like the first one for it's ellegant simplicity, the more I look at it, the more Pythonic it feels to me... after all, what is more Pythonic than a one liner with zip, asterisk argument expansion, list comprehensions, list slicing, list concatenation and "range"?

    def ntuples(lst, n):
        return zip(*[lst[i:]+lst[:i] for i in range(n)])
    

    The itertools version should be efficient enough even for large lists...

    from itertools import *
    def ntuples(lst, n):
        return izip(*[chain(islice(lst,i,None), islice(lst,None,i)) for i in range(n)])
    

    And a version for non-indexable sequences:

    from itertools import *
    def ntuples(seq, n):
        iseq = iter(seq)
        curr = head = tuple(islice(iseq, n))
        for x in chain(iseq, head):
            yield curr
            curr = curr[1:] + (x,)
    

    Anyway, thanks everybody for your suggestions! :-)

提交回复
热议问题