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

时间:2016-11-27 10:22:00

标签: python arrays

我基本上评估了积分,因为辛普森和其他来自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]

2 个答案:

答案 0 :(得分:0)

试试这个

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)

答案 1 :(得分:-1)

您可以使用tolist()
https://stackoverflow.com/a/31517371/7215503

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.tolist().index(t)-1]**2/2)))

print('peer ', peer)

您需要将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])