I am trying to use list comprehension to replace this for loop. My list is
test_list = [3, 4, 6, 3, 8, 4, 7, 8, 12, 14, 1, 6, 7, 3, 7, 8, 3, 3, 7]
The function is
import numpy as np
def ema(x, n):
x = np.array(x)
emaint = np.zeros(len(x))
k = 2 / float(n + 1)
emaint[0:n] = np.average(x[:n])
for i in range(n, len(x)):
emaint[i] = (x[i] * k) + (emaint[i - 1] * (1 - k))
return emaint
The result for if I call ema(test_list, 5) will be
[4.8 4.8 4.8 4.8 4.8 4.53333333 5.35555556 6.23703704 8.15802469 10.10534979 7.0702332 6.7134888 6.80899253 5.53932835 6.0262189 6.68414594 5.45609729 4.63739819 5.42493213]
I have tried this
import numpy as np
def ema_compr(x, n):
x = np.array(x)
emaint = np.zeros(len(x))
k = 2 / float(n + 1)
emaint[0:n] = np.average(x[:n])
emaint[n:] = [(x[i] * k) + (emaint[i - 1] * (1 - k)) for i in range(n, len(x))]
return emaint
however the result is different if I call ema_compr(test_list, 5):
[4.8 4.8 4.8 4.8 4.8 4.53333333 2.33333333 2.66666667 4. 4.66666667 0.33333333 2. 2.33333333 1. 2.33333333 2.66666667 1. 1. 2.33333333]
- I would like if it is possible to get a list comprehension.
- Is the result of the list comprehension different because I am tying to access a non-created element?