views:

72

answers:

3

How would you write a list comprehension in python to generate a series of n-1 deltas between n items in an ordered list?

Example:

L = [5,9,2,1,7]
RES = [5-9,9-2,2-1,1-7] = [4,7,1,6] # absolute values
+4  A: 

The recipes section of the itertools documentation includes source code for a function called pairwise that you can use for this purpose:

from itertools import *

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    b.next()
    return izip(a, b)

You can copy and paste this into your file. With this function defined it is quite simple to do what you want:

l = [5, 9, 2, 1, 7]
print [abs(a-b) for a,b in pairwise(l)]

Result

[4, 7, 1, 6] 
Mark Byers
+2  A: 

Just figured it out:

[abs(x-y) for x,y in zip(L[:-1], L[1:])]
Yuval A
For large lists you might want to use itertools.izip instead of zip. http://docs.python.org/library/itertools.html#itertools.izip
Mark Byers
I don't like the unnecessary duplication of the original list.
jellybean
+4  A: 
RES = [abs(L[i]-L[i+1]) for i in range(len(L)-1)]
jellybean