pairwise traversal of a list or tuple

后端 未结 6 1477
走了就别回头了
走了就别回头了 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:15

    It's ok to use range. However, programming (like maths) is about building on abstractions. Consecutive pairs [(x0, x1), (x1, x2), ..., (xn-2, xn-1)], are called pairwise combinations. See an example in the itertools docs. Once you have this function in your toolset, you can write:

    for x, y in pairwise(xs):
        print(y - x)
    

    Or used as a generator expression:

    consecutive_diffs = (y - x for (x, y) in pairwise(xs))
    

提交回复
热议问题