Skip to main content
 首页 » 编程设计

python之在 Python 中将上一个和下一个元素相乘

2024年10月01日8mfrbuaa

我一直在尝试用 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' 

我实际上也尝试过 map,但 id 没有用。

请您参考如下方法:

您需要从 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 

输出:

对于一阶导数:

[1.5, 4.0, 7.5, 12.0]