我一直试图将Python中的上一个和下一个数字相乘,但我总是得到一个不同的错误。这就是我一直在做的事情:
u=[1, 41, 56, 80]
def Filter(vel):
global firstDerivative
firstDerivative = np.repeat(None, len(vel))
for index, obj in enumerate(vel):
if index !=0 & index !=len(vel-1):
firstDerivative = (vel[index-1]*vel[index+1])/2
Filter(u)
出现以下错误:
TypeError: unsupported operand type(s) for -: 'list' and 'int'
我实际上也试过了地图,但是id没有用。
答案 0 :(得分:1)
你需要从1迭代到-1,并在你去的时候填充firstDerivative
数组:
def Filter(vel):
global firstDerivative # you are probably better advised to return firstDerivative instead
firstDerivative = [0] * (len(vel) - 2)
for ndx in range(1, len(vel) - 1):
firstDerivative[ndx-1] = vel[ndx-1] * vel[ndx+1] / 2
firstDerivative = []
u = [1, 2, 3, 4, 5, 6]
Filter(u)
firstDerivative
for firstderivative:
[1.5, 4.0, 7.5, 12.0]
答案 1 :(得分:1)
自numpy
被标记后,您只需使用a[:-2]*a[2:]/2
:
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> a[:-2]
array([1, 2, 3, 4])
>>> a[2:]
array([3, 4, 5, 6])
>>> a[:-2]*a[2:]/2
array([ 1.5, 4. , 7.5, 12. ])
请注意,它与衍生物无关。您应该更改代码或变量名称。衍生物将是差异,例如与(a[i+1] - a[i])/2
:
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> (a[2:] - a[:-2])/2
array([ 1., 1., 1., 1.])
>>> np.ediff1d(a)
array([1, 1, 1, 1, 1])