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

后端 未结 6 2156
忘掉有多难
忘掉有多难 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:19

    You can do a list comprehension:

    >>> A = [1, 10, 100, 50, 40]
    >>> l=[A[0]]+A
    >>> [abs(l[i-1]-l[i]) for i in range(1,len(l))]
    [0, 9, 90, 50, 10]
    

提交回复
热议问题