Several generators from one loop / returning a tuple of generators

﹥>﹥吖頭↗ 提交于 2019-12-11 08:05:14

问题


I would like to generate two generators with one loop for computational efficiency.

My code is running a simulation where an observation is sampled (computationally expensive) and a metric computed (computationally expensive). I am interested in results where the metric meets a certain criterion.

def simulate(N):
    for _ in range(0, N):               # where N is typically a large integer
        obs = sampleFromSpace()         # computationally intensive
        metric = computeMetric(obs)     # computationally intensive
        if(meets_criterion(metric)):     # note the constraint on metric to filter obs!
            yield (obs, metric)

This code returns a generator of tuple, but what I want is a generator for the obs and a generator for the metric

Is there any way to create these 2 iterators without looping twice or storing all obs in a list?

Objective:

obs_gen, metric_gen = simulate(1e9)

来源:https://stackoverflow.com/questions/47166701/several-generators-from-one-loop-returning-a-tuple-of-generators

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