简体   繁体   English

Python联合枚举多个变量

[英]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. 当然,假设两个var数组的长度相同。

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 . 您枚举varszip的元组。

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. 尽管由于您使用的是numpy数组,但是我敢肯定,有一种更好的方法可以实现相同的目标,而无需使用python for循环。

Also took the liberty of changing the names of variables since you were usign y in two different contexts and could be confusing. 也改变了变量的名字,因为你usign的自由y在两个不同的上下文中,可能会造成混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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