Returning values from inside a while loop in python

梦想与她 提交于 2019-12-11 09:35:25

问题


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.

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?

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

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.


回答1:


Create a generator instead.

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)

EDIT:

Or perhaps a coroutine.

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)



回答2:


what you are looking for is yield

def func():
    while True:
        yield "hello"


for x in func():
    print(x):

generators can also be written like list comprehensions:

have a look at this question:

What does the "yield" keyword do in Python?




回答3:


If I understand you and the code you want to do.

I may think of trying to find equations of position, velocity and acceleration with respect to time.

So you won't need to keep, the while loop running, what you need is to convert it to a function, and using the time difference between the 2 function calls, you can perform the calculations you want, only when you call the function, rather than having the while loop running all the time.



来源:https://stackoverflow.com/questions/11172496/returning-values-from-inside-a-while-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!