Reputation: 1690
I have a list, a time series, s
. I would like to efficiently take the "self difference" of the list: output[n] = s(n)-s(n+1)
. What's an efficient (in terms of time) way of doing this?
My eventual goal is to have a list representing this below, with this question implementing the first step:
∑[∡s1(t)−∡s1(t−1)]⋅[∡s2(t+τ)−∡s2(t−1+τ)]
Upvotes: 0
Views: 219
Reputation: 44475
Consider a third-party tool, more_itertools.difference
.
import more_itertools as mit
list(mit.difference([0, 1, 3, 6, 10]))
# [0, 1, 2, 3, 4]
Upvotes: 0
Reputation: 3280
If you want an efficient way, use numpy: https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.diff.html
import numpy as np
s = np.array([1, 2, 4, 7, 0])
output = np.diff(s)
print(output) # [ 1 2 3 -7]
Upvotes: 4
Reputation: 77837
Use a simple list comprehension:
output = [s[n] - s[n+1] for n in range(len(n)-1)]
Let the Python run-time system do any optimizations it wants; this method saves your time as programmer and maintainer.
Upvotes: 1