Iterate a list as pair (current, next) in Python

前端 未结 10 1721
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 22:54

I sometimes need to iterate a list in Python looking at the \"current\" element and the \"next\" element. I have, till now, done so with code like:

for curre         


        
10条回答
  •  攒了一身酷
    2020-11-21 23:08

    I am really surprised nobody has mentioned the shorter, simpler and most importantly general solution:

    Python 3:

    from itertools import islice
    
    def n_wise(iterable, n):
        return zip(*(islice(iterable, i, None) for i in range(n)))
    

    Python 2:

    from itertools import izip, islice
    
    def n_wise(iterable, n):
        return izip(*(islice(iterable, i, None) for i in xrange(n)))
    

    It works for pairwise iteration by passing n=2, but can handle any higher number:

    >>> for a, b in n_wise('Hello!', 2):
    >>>     print(a, b)
    H e
    e l
    l l
    l o
    o !
    
    >>> for a, b, c, d in n_wise('Hello World!', 4):
    >>>     print(a, b, c, d)
    H e l l
    e l l o
    l l o
    l o   W
    o   W o
      W o r
    W o r l
    o r l d
    r l d !
    

提交回复
热议问题