Finding the difference between consecutive numbers in a list (Python)

后端 未结 6 2147
忘掉有多难
忘掉有多难 2020-12-20 17:48

Given a list of numbers, I am trying to write a code that finds the difference between consecutive elements. For instance, A = [1, 10, 100, 50, 40] so the outp

6条回答
  •  情深已故
    2020-12-20 18:02

    You can do:

    [y-x for x, y in zip(A[:-1], A[1:])] 
    
    
    >>> A = [1, 10, 100, 50, 40]
    >>> [y-x for x, y in zip(A[:-1], A[1:])]
    [9, 90, -50, -10]
    

    Note that the difference will be negative if the right side is smaller, you can easily fix this (If you consider this wrong), I'll leave the solution for you.

    Explanation:

    The best explanation you can get is simply printing each part of the list comprehension.

    • A[:-1] returns the list without the last element: [1, 10, 100, 50]
    • A[1:] returns the list without the first element: [10, 100, 50, 40]
    • zip(A[:-1], A[1:]) returns [(1, 10), (10, 100), (100, 50), (50, 40)]
    • The last step is simply returning the difference in each tuple.

提交回复
热议问题