【问题标题】:Multiply previous and next elements in Python在 Python 中将上一个和下一个元素相乘
【发布时间】:2018-05-10 08:56:10
【问题描述】:

我一直在尝试将 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不行。

【问题讨论】:

  • 你的数据是什么?
  • 给出你的输入数据!?你这里的“你”是什么?
  • 除了np.repeat的使用之外,numpy还有什么用?
  • 对不起,我编辑了它
  • 错误在len(vel-1)vel 是一个列表。没有为此定义减号。 len(vel)-1 怎么样?

标签: python python-3.x numpy indexing


【解决方案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

输出:

对于一阶导数:

[1.5, 4.0, 7.5, 12.0]

【讨论】:

  • 这样我得到一个结果。我想要一个与之交互的列表
  • 我之前尝试过这样做,方法相同。我收到以下 TypeError: unsupported operand type(s) for -: 'list' and 'int'
【解决方案2】:

由于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])

【讨论】:

  • 感谢 Eric,我使用的方法就是这样称呼它的。所以我使用相同的名字来跟随它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
相关资源
最近更新 更多