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

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

    To answer your question about solving for the general case:

    import itertools
    
    def pair(series, n):
        s = list(itertools.tee(series, n))
        try:
            [ s[i].next() for i in range(1, n) for j in range(i)]
        except StopIteration:
            pass
        while True:
            result = []
            try:
                for j, ss in enumerate(s):
                    result.append(ss.next())
            except StopIteration:
                if j == 0:
                    break
                else:
                    s[j] = iter(series)
                    for ss in s[j:]:
                        result.append(ss.next())
            yield result
    

    The output is like this:

    >>> for a in pair(range(10), 2):
    ...     print a
    ...
    [0, 1]
    [1, 2]
    [2, 3]
    [3, 4]
    [4, 5]
    [5, 6]
    [6, 7]
    [7, 8]
    [8, 9]
    [9, 0]
    >>> for a in pair(range(10), 3):
    ...     print a
    ...
    [0, 1, 2]
    [1, 2, 3]
    [2, 3, 4]
    [3, 4, 5]
    [4, 5, 6]
    [5, 6, 7]
    [6, 7, 8]
    [7, 8, 9]
    [8, 9, 0]
    [9, 0, 1]
    

提交回复
热议问题