简体   繁体   English

Python生成器函数混淆

[英]Python generator function confusion

Hey so I am working on a program that requires a day/night cycle.嘿,所以我正在开发一个需要昼夜循环的程序。 Here is the function that I made to get it to start working:这是我用来让它开始工作的函数:

def epoch():
    for i in range(0,varb.run_number):
        print("it is now day")
        epoch_state = 1
        yield epoch_state
        time.sleep(varb.day_night_length)
        print("it is now night")
        epoch_state = 0 
        yield epoch_state
        time.sleep(varb.day_night_length)

I can find nothing wrong with it, but when I call it I get this:我发现它没有任何问题,但是当我调用它时,我得到了这个:

<generator object epoch at 0x01036670>

Any ideas on how to fix this?有想法该怎么解决这个吗?

PS The idea here is to run the cycle while printing out the state and returning the state PS这里的想法是在打印出状态并返回状态的同时运行循环

PPS anything with varb. PPS 任何带有 varb 的东西。 is a global with an unimportant numerical value是一个不重要的数值的全局变量

There is no error here.这里没有错误。 The function is working correctly.该功能工作正常。

You created a generator function by using yield expressions.您使用yield表达式创建了一个生成器函数 You now need to iterate over your generator .您现在需要遍历您的 generator Until you do, the generator is paused.在您这样做之前,生成器将暂停。

You could use list() for that:你可以使用list()

result = list(epoch())

or a for loop:for循环:

for result in epoch():
    print(result)

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

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