Several generators from one loop / returning a tup

2019-07-28 09:05发布

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)

0条回答
登录 后发表回答