简体   繁体   中英

Python joint enumerate with multiple variables

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM