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

前端 未结 10 1716
隐瞒了意图╮
隐瞒了意图╮ 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:01

    This is now a simple Import As of 16th May 2020

    from more_itertools import pairwise
    for current, next in pairwise(your_iterable):
      print(f'Current = {current}, next = {nxt}')
    

    Docs for more-itertools Under the hood this code is the same as that in the other answers, but I much prefer imports when available.

    If you don't already have it installed then: pip install more-itertools

    Example

    For instance if you had the fibbonnacci sequence, you could calculate the ratios of subsequent pairs as:

    from more_itertools import pairwise
    fib= [1,1,2,3,5,8,13]
    for current, nxt in pairwise(fib):
        ratio=current/nxt
        print(f'Curent = {current}, next = {nxt}, ratio = {ratio} ')
    

提交回复
热议问题