Possible Duplicate:
Python - Differences between elements of a list
I have a list and I want to find difference between consecutive elements:
a = [0, 4, 10, 100] find_diff(a) >>> [4,6,90]
How would you code find_diff() function? I can code this with "for" iterator but I am sure there are very simple ways to do it with a simple one liner.
You could utilize enumerate
, zip
and list comprehensions:
>>> a = [0, 4, 10, 100] # basic enumerate without condition: >>> [x - a[i - 1] for i, x in enumerate(a)][1:] [4, 6, 90] # enumerate with conditional inside the list comprehension: >>> [x - a[i - 1] for i, x in enumerate(a) if i > 0] [4, 6, 90] # the zip version seems more concise and elegant: >>> [t - s for s, t in zip(a, a[1:])] [4, 6, 90]
Performance-wise, there seems to be not too much variance:
In [5]: %timeit [x - a[i - 1] for i, x in enumerate(a)][1:] 1000000 loops, best of 3: 1.34 µs per loop In [6]: %timeit [x - a[i - 1] for i, x in enumerate(a) if i > 0] 1000000 loops, best of 3: 1.11 µs per loop In [7]: %timeit [t - s for s, t in zip(a, a[1:])] 1000000 loops, best of 3: 1.1 µs per loop
Use the recipe for pairwise
from the itertools documentation:
from itertools import izip, tee def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b)
Use it like this:
>>> a = [0, 4, 10, 100] >>> [y-x for x,y in pairwise(a)] [4, 6, 90]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With