如何使用需要很多秒才能返回值的函数“实时”更新变量
问题描述:
应该使用什么逻辑来实时更新当前均值等变量?如何使用需要很多秒才能返回值的函数“实时”更新变量
例如,在下面的脚本obs_mean()
中,通过监听传入的传感器数据产生一个均值。功能listen_to_observations()
是一个与真实传感器数据功能类似的示例功能。
如何可以将该值current_mean
被更新使用obs_mean(5)
每秒/实时(其需要5秒钟的数据,并且需要5秒的返回值)?
import numpy as np
import random
import time
current_mean = None
def listen_to_observations():
#listen to a stream of observations
time.sleep(1)
yield random.random()
def obs_mean(seconds):
array = [listen_to_observations().next() for i in range(seconds)]
return np.array(array).mean()
这个逻辑怎么样?我正在使用Python 3.5。
答
你可以只打破了你的阵列行成单独的语句,并计算平均每次观察后:
import numpy as np
import random
import time
current_mean = None
def listen_to_observations():
#listen to a stream of observations
time.sleep(1)
yield random.random()
def obs_mean(seconds):
array = []
for i in range(seconds):
array.append(listen_to_observations().next())
current_mean = np.array(array).mean()
print('current_mean = {}'.format(current_mean))
return current_mean
if __name__ == '__main__':
obs_mean(5)
我的输出:
current_mean = 0.193142347659
current_mean = 0.212120380098
current_mean = 0.355774933848
current_mean = 0.362840457341
current_mean = 0.312662693142
如果平均每5后计算秒,那么更新“current_mean”变量有什么用?它当然会保持不变,直到你计算出新的均值。 – kmario23
不完全。如果在10:00:00调用函数obs_mean(5),它将在10:00:05返回值。然而,在10:00:06,从10:00:01到10:00:06可能会有更新的观测值。那有意义吗? – Greg