从python中的while循环内部返回值 [英] Returning values from inside a while loop in python

查看:103
本文介绍了从python中的while循环内部返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是一个简单的问题还是不可能的问题,但我找不到任何关于它的信息,所以我想我会问它.

I don't know if this is a simple question or impossible or anything, but I couldn't find anything on it so I figured I would ask it.

是否可以在while循环仍在运行时从该循环中返回值?基本上我想要做的是让一个向量在一个 while 循环中不断更新,但能够在不停止 while 循环的情况下在被询问时返回值.这可能吗?我是否只需要分解程序并将 while 循环放在一个单独的线程中,还是可以在一个函数中完成?

Is it possible to return values from a while loop while that loop is still running? Basically what I want to do is have a vector constantly updating within a while loop, but able to return values when asked without stopping the while loop. Is this possible? Do I just have to break up the program and put the while loop in a separate thread, or can I do it within one function?

此外,我更喜欢一种计算量不高(显然)的方法,并且与速率限制的 while 循环兼容,因为这个方法肯定会受到速率限制.

Also I would prefer a method that is not computationally intensive (obviously), and one compatible with a rate-limited while loop as this one will certainly be rate-limited.

再说一次,如果这是一个愚蠢的问题,请告诉我,我会删除它,但我找不到关于此的文档.

Again, if this is a stupid question just tell me and I will delete it, but I wasn't able to find documentation on this.

我正在尝试使用的代码:

Code I am trying to implement this with:

def update(self, x_motion, y_motion, z_motion):
        self.x_pos += self.x_veloc
        self.y_pos += self.y_veloc
        self.z_pos += self.z_veloc
        self.x_veloc += self.x_accel
        self.y_veloc += self.y_accel
        self.z_veloc += self.z_accel
        self.x_accel = x_motion[2]
        self.y_accel = y_motion[2]
        self.z_accel = z_motion[2]
while True:
self.update(x_motion, y_motion, z_motion)

print vector.x_accel

至少有一些类似的东西.重要的是这些在 while 循环之外返回,以便 while 循环在后台运行,但它只在被询问时才给出结果,或者类似的东西.

Something along those lines at least. It is important that these return outside of the while loop, so that the while loop runs in the background, but it only gives results when asked, or something like that.

推荐答案

改为创建生成器.

def triangle():
  res = 0
  inc = 1
  while True:
    res += inc
    inc += 1
    yield res

t = triangle()
print next(t)
print next(t)
print next(t)
print next(t)

或者一个协程.

def summer():
  res = 0
  inc = 0
  while True:
    res += inc
    inc = (yield res)

s = summer()
print s.send(None)
print s.send(3)
print s.send(5)
print s.send(2)
print s.send(4)

这篇关于从python中的while循环内部返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆