I am solving a problem in which it is necessary to calculate the finite differences Δy. We have the original list of y values: [0.0000, 0.0016, 0.5875, 0.8087, 0.9509, 1.0000]
.
We need to get the differences:
из последующего значения вычесть предыдущее (например: 0.0016-0.000; 0.5875-0.0016 и так далее) - на выходе нам нужен список, где значений на одно меньше; продолжим вычитание с рассчитанными разностями - на выходе снова список, где значений еще на одно меньше. Так идем до тех пор, пока не останется одно значение, из которого вычитать нечего.
As a result, I would like to have a list of lists with finite differences: [ [Δ1, Δ2, Δ3], [Δ4, Δ5], [Δ6] ]
.
I implemented a code where I get None values, and in each nested list they do not become one less - this is not what I want to have in the output:
[[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None]]
Here is my code:
my_list = [0.0000, 0.0016, 0.5875, 0.8087, 0.9509, 1.0000]
n=3
diff_list = []
data = [[diff_list.append(y-x) for x, y in zip(my_list[0::], my_list[1::])] for i in range(0, n)]
print(data)
CodePudding user response:
Please, post the text in English! Also, provide the result you are expecting from that example.
However, if I understood correctly:
import numpy as np
my_list = [0.0000, 0.0016, 0.5875, 0.8087, 0.9509, 1.0000]
result = [np.diff(my_list, n=d) for d in range(1, len(my_list))]
Here, result
would be:
[array([0.0016, 0.5859, 0.2212, 0.1422, 0.0491]),
array([ 0.5843, -0.3647, -0.079 , -0.0931]),
array([-0.949 , 0.2857, -0.0141]),
array([ 1.2347, -0.2998]),
array([-1.5345])]
However, if my_list
is very large, you might want to do this, to save computations:
result = []
for d in range(1, len(my_list)):
result.append(np.diff(my_list if d == 1 else result[-1]))