[英]Preventing for loop in Python for a summation function
I have a vector x of length 10
.我有一个长度为10
的向量x 。 I want to perform the following summation in Python:我想在 Python 中执行以下求和:
sum |x_{i} - x_{i-1}| over all i
I have written the below code, but I am sure there is a more optimal way in order to prevent the for loop.我已经编写了以下代码,但我确信有一种更优化的方法可以防止 for 循环。 I need your suggestions.我需要你的建议。
import numpy as np
x = np.random.rand(10,1)
sum = 0
#note that in Python the index starts at 0
for i in range(10-1):
sum = sum + abs(x[i+1] - x[i])
Any help will be very appreciated!任何帮助将不胜感激!
Sure, you can do something like:当然,您可以执行以下操作:
np.abs(x[1:] - x[:-1]).sum()
Also, if you need to maintain the result as a vector, you can use:此外,如果您需要将结果保持为向量,您可以使用:
np.abs(x[1:] - x[:-1]).sum(axis=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.