繁体   English   中英

如何在不结束Python函数的情况下返回变化的变量?

[英]How can I return a changing variable without ending the function in Python?

我正在尝试将下面代码的答案返回到变量中,该变量应该每5秒更改一次,因此我无法使用“返回”,因为它结束了函数。

例:

from time import sleep

def printit():
    cpt = 1
    while True:
        if cpt < 3:
            number = ("images[" + str(cpt) + "].jpg")
            return number #here is the return
            sleep(5)
            cpt+=1
        else:
            printit()

answer = printit() 
print(answer) #only 1 answer is printed, then the function ends because of the 'return'

解决此问题的解决方案是什么?

可变答案应每5秒更改一次,而不结束功能。

解决此问题的解决方案是什么? 可变答案应每5秒更改一次,而不结束功能。

这是一种基于生成器功能的方法

from time import sleep

def printit():
    cpt = 1
    while True:
        if cpt < 3:
            number = ("images[" + str(cpt) + "].jpg")
            yield number #here is the return
            sleep(5)
            cpt+=1
        else:
            for number in printit():
                yield number


for number in printit():
    print number

这将使进程一直运行,直到for循环不再接收任何值为止。 要优雅地停止它,可以向生成器发送一个值:

gen = printit()
for i, number in enumerate(gen):
    print i, number
    if i > 3:
        try: 
            gen.send(True)
        except StopIteration:
            print "stopped"

为此,请修改yield语句,如下所示:

(...)
stop = yield number #here is the return
if stop:
   return
(...)

根据您要实现的目标,这可能会或可能不会提供足够的并行级别。 如果您想进一步了解基于生成器的协程,那么David Beazley的这些非常有见地的论文和视频是个好习惯。

如果要无限计数,则应将itertools.count与生成器函数一起使用,该函数可以使您简洁地编写代码:

from itertools import count
from time import sleep

def printit():
    cn = count(1)
    for i in iter(cn.next, 0):
        yield "images[{}].jpg".format(i)
        sleep(5)

for answer in printit():
    print(answer)

暂无
暂无

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

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