跳过数组中的第一项,并在for循环python中使用当前项和上一项

跳过数组中的第一项,并在for循环python中使用当前项和上一项,python,arrays,Python,Arrays,我基本上计算了一个积分,因为辛普森一家和其他来自scipy的积分近似并没有给出准确的答案。在创建了一个名为“bounds”的数组,并使用不同的边界来计算积分后,我希望使用for循环遍历该数组,并在函数中使用积分的连续上界和下界(或者在for循环中,在跳过第一项后,使用当前项和上一项)。这就是我所做的 import numpy as np turns = [0, 200, 400, 600, 800, 1000, 1200, 1400] bounds = np.cumsum(turns) pri

我基本上计算了一个积分,因为辛普森一家和其他来自scipy的积分近似并没有给出准确的答案。在创建了一个名为“bounds”的数组,并使用不同的边界来计算积分后,我希望使用for循环遍历该数组,并在函数中使用积分的连续上界和下界(或者在for循环中,在跳过第一项后,使用当前项和上一项)。这就是我所做的

import numpy as np

turns = [0, 200, 400, 600, 800, 1000, 1200, 1400]
bounds = np.cumsum(turns)
print('Lower and Upper Integral bounds ', bounds)
peer = []

for t in bounds[1:]:
    peer.append((0.304*(t**2/2))-(0.304*(bounds[bounds.index(#previous item)]**2/2)))

print('peer ', peer)
输出

Lower and Upper Integral bounds  [   0  200  600 1200 2000 3000 4200 5600]

AttributeError: 'numpy.ndarray' object has no attribute 'index'
期望输出值

Lower and Upper Integral bounds  [   0  200  600 1200 2000 3000 4200 5600]
peer [6080, 48640, 164160, 389120, 760000, 1313280, 2085440]
试试这个

import numpy as np

turns = [0, 200, 400, 600, 800, 1000, 1200, 1400]
bounds = np.cumsum(turns)
print('Lower and Upper Integral bounds ', bounds)
peer = []

for index,t in enumerate(bounds[1:]):
    peer.append((0.304*(t**2/2))-(0.304*(bounds[index]**2/2)))
print('peer ', peer)

您可以使用to
tolist()

您需要将
bounds[bounds.index(t-1)]
更改为
bounds[bounds.index(t)-1]

这是结果。

('Lower and Upper Integral bounds ', array([   0,  200,  600, 1200, 2000, 3000, 4200, 5600]))
('peer ', [6080.0, 48640.0, 164160.0, 389120.0, 760000.0, 1313280.0, 2085440.0])

我对“scipy没有给出准确的结果”感到非常惊讶。我还没有尝试scipy的所有集成选项。我相信有一个函数可以给出准确的答案。我只是发现手工做积分比寻找最好的积分函数更快,只需替换边界即可。谢谢,有时候自己编写函数更容易/更好,因为你100%知道函数在做什么。我只是好奇scipy一开始是如何/为什么不工作的,没有冒犯的意思。
('Lower and Upper Integral bounds ', array([   0,  200,  600, 1200, 2000, 3000, 4200, 5600]))
('peer ', [6080.0, 48640.0, 164160.0, 389120.0, 760000.0, 1313280.0, 2085440.0])