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
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
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]