M. Beining
M. Beining

Reputation: 99

Loop over multiple generators together

I need to get the result of each generator at the same time but the number of generators can be anything from 1 to 10.

My question is probably related to this question: Loop over two generator together

Is it possible to generalize this for an arbitrary number of generators which are in a list? Something like (not working)

generators = [gen1, gen2, gen3, ....]
for *data in *generators:
    #do something, e.g. average data along axis and write out

Upvotes: 3

Views: 1140

Answers (1)

yatu
yatu

Reputation: 88226

IIUC you want zip for this. Here's a simple example taking the sum:

generators = [(1,2), (3,4), (5,6)]
[sum(i) for i in zip(*generators)]

# [9, 12]

Or itertools.zip_longest as @alexis suggests, if the generators could differ in length and you'd like to iterate until the longest one is consumed:

generators = [(1,2), (3,4), (5,6,0)]
[sum(i) for i in zip_longest(*generators, fillvalue=0)]
# [9, 12, 0]

Upvotes: 3

Related Questions