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

本秂侑毒 提交于 2019-12-05 15:08:11

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.

The simplest (laziest) solution is to use the numpy function diff:

>>> A = [1, 10, 100, 50, 40]
>>> np.diff(A)
array([  9,  90, -50, -10])

If you want the absolute value of the differences (as you've implied by your question), then take the absolute value of the array.

[abs(j-A[i+1]) for i,j in enumerate(A[:-1])]

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]

For a longer recursive solution more in line with your original approach:

def deviation(A) :
    if len(A) < 2 :
        return []
    else :
        return [abs(A[0]-A[1])] + deviation(A[1:])

Your bracket issue is with your recursive call. Since you have your [deviation(a[1: ])] in its own [] brackets, with every recursive call you're going to be creating a new list, resulting in your many lists within lists.

In order to fix the None issue, just change your base case to an empty list []. Now your function will add 'nothing' to the end of your recursively made list, as opposed to the inherent None that comes with a blank return'

Actually recursion is an overkill:

def deviation(A):
    yield 0
    for i in range(len(A) - 1):
        yield abs(A[i+1] - A[i])

Example:

>>> A = [3, 5, 2]
>>> list(deviation(A))
[0, 2, 3]

EDIT: Yet, another, even simplier and more efficient solution would be this:

def deviation(A):
    prev = A[0]
    for el in A:
        yield abs(el - prev)
        prev = el
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!