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

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

    Here's a version that supports an optional start index (for example to return (4, 0) as the first pair, use start = -1:

    import itertools
    
    def iterrot(lst, start = 0):
    
        if start == 0:
            i = iter(lst)
        elif start > 0:
            i1 = itertools.islice(lst, start, None)
            i2 = itertools.islice(lst, None, start)
            i = itertools.chain(i1, i2)
        else:
            # islice doesn't support negative slice indices so...
            lenl = len(lst)
            i1 = itertools.islice(lst, lenl + start, None)
            i2 = itertools.islice(lst, None, lenl + start)
            i = itertools.chain(i1, i2)
        return i
    
    
    def iterpairs(lst, start = 0):
    
        i = iterrot(lst, start)     
    
        first = prev = i.next()
        for item in i:
            yield prev, item
            prev = item
        yield prev, first
    
    
    def itertrios(lst, start = 0):
    
        i = iterrot(lst, start)     
    
        first = prevprev = i.next()
        second = prev = i.next()
        for item in i:
            yield prevprev, prev, item
            prevprev, prev = prev, item
    
        yield prevprev, prev, first
        yield prev, first, second
    
    0 讨论(0)
提交回复
热议问题