简体   繁体   English

如何在循环的第一次迭代中传递一些初始值,然后在 python 的后续迭代中传递派生值?

[英]How to pass some initial value in the first iteration of the loop and then pass the derived values in the subsequent iterations in python?

initial_state = 40

def funct_1(x):
    return y

def funct_2(y):
    return z

def main():
    funct_1(x)
    funct_2(y)

for i in range(10):
    main()

In the first iteration, I want input to funct1 ie x = initial_state and from the second iteration onwards, I want output of funct_2 ie z becomes input to funct_1.在第一次迭代中,我希望输入到funct1,即x = initial_state,从第二次迭代开始,我想要funct_2 的output,即z 成为funct_1 的输入。 Please let me know how can I implement this in python.请让我知道如何在 python 中实现这一点。

Normally, this should work:通常,这应该有效:

initial_state = 40

def funct_1(x):
    return y

def funct_2(y):
    return z

def main():
    for i in range(10):
        if i == 1:
            funct_1(x)
        else:
            funct_2(y)

if __name__ == '__main__':
    main()

Straightforward way is following:直截了当的方法如下:

def funct_1(x):
    y = x + 1
    return y


def funct_2(y):
    z = y + 1
    return z


def main(x):
    y = funct_1(x)
    z = funct_2(y)
    return z


state = 40
for i in range(10):
    state = main(state)
    

This should work: In the first iteration you have your default value of x and in all iterations after that x is the output of funct_2().这应该有效:在第一次迭代中,您有默认值 x,并且在之后的所有迭代中,x 是 funct_2() 的 output。

x = init_state
def main():
   y = funct_1(x)
   x = funct_2(y)

for i in range(10):
   main()

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

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