So I would like to iterate over two lists simultaneously and I also need the index as done with the following code. Both are straightforward to me, but is it possible two use enumerate in the second case as well? Of course, assuming both var arrays are of the same length.
import numpy as np
def _eqn(y, variables, sign=-1.0):
f = 0
for i,x in enumerate(variables):
f += x/(1+0.06)**(i+1)
return float(sign*(y + f))
_eqn(1,np.array([1,1]))
def _eqn2(y, vars1, vars2, sign=-1.0):
f = 0
n = len(vars1)
for x,y,i in zip(vars1, vars2, range(n)):
f += (x+y)/(1+0.06)**(i+1)
return float(sign*(y + f))
_eqn2(1,np.array([1,1]),np.array([1,1]))
Yes, it is possible... although with a slight change
def _eqn2(y, vars1, vars2, sign=-1.0):
f = 0
for i, (v1,v2) in enumerate(zip(vars1, vars2)):
f += (v1+v2)/(1+0.06)**(i+1)
return float(sign*(y + f))
You enumerate tuples of the zip
of your vars
.
Although since you're working with numpy
arrays, I'm sure that there is a better way to achieve this same goal without using a python for
loop.
Also took the liberty of changing the names of variables since you were usign y
in two different contexts and could be confusing.