Multiple generators from a single cycle / returning tuple of generators

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

My code launches a simulation where selective observation (computationally expensive) and a computed metric (computationally expensive) are performed. I'm interested in results where the metric meets a specific 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 tuple generator, but I want a generator for obsand a generator formetric

Is there a way to create these 2 iterators without repeating the loop or saving everyone obsin the list?

Purpose:

obs_gen, metric_gen = simulate(1e9)
+1
source share

All Articles