pairwise traversal of a list or tuple

后端 未结 6 1462
走了就别回头了
走了就别回头了 2020-12-03 14:11
a = [5, 66, 7, 8, 9, ...]

Is it possible to make an iteration instead of writing like this?

a[1] - a[0]

a[2] - a[1]

a[3] - a[2]

         


        
6条回答
  •  死守一世寂寞
    2020-12-03 14:29

    I would recommend to use awesome more_itertools library, it has ready-to-use pairwise function:

    import more_itertools
    
    for a, b in more_itertools.pairwise([1, 2, 3, 4, 5]):
        print(a, b)
    # 1 2
    # 2 3
    # 3 4
    # 4 5
    

    It will save you from writing your own (likely buggy) implementation. For example, most of implementations on this page don't handle the case with empty iterable correctly -- generator function should never raise StopIteration, this behavior considered deprecated and causes DeprecationWarning in Python 3.6. It won't work in Python 3.7 at all.

提交回复
热议问题