Search code examples
pythonlistintegral

iterate over a list by pre-defined steps


How to iterate over a list with defined steps and not in each item in the list? I want to be able to jump some items.

t = np.linspace(0,100,1000)
Fs = 6000
f = 200

func = 50*np.sin(2 * np.pi * f * t / Fs)+50

idx = [9 140 309 439 609 739 908]
for i in (idx):
        it = integrate.simps(func[i], t[i])
        print(it)

>> gives me this :
5428.010261680331
5428.010261680331
5428.010261680331
5428.010261680331
5428.010261680331
5428.010261680331
5428.010261680331

''' which is logical, because it iterates over every element,
but how to iterate like the following : 
I want to do integral of func from:
idx 1 to 2
idx 3 to 4 
idx 5 to 6
idx 7 to end which doesn't exist because the list is just 7 items
  so that it gives me only four values'''

Solution

  • You want to iterate through the values in idx in pairs?

    This post Iterating over every two elements in a list has some ways of doing that. Not sure how you want to handle the edge-case of the last element not having a next element though.