Let's say I have a Python list representing ranges for some variables:
conditions = [['i', (1, 5)], ['j', (1, 2)]]
This represents that variable i
ranges from 1 to 5, and inside that loop variable j
ranges from 1 to 2. I want a dictionary for each possible combination:
{'i': 1, 'j': 1}
{'i': 1, 'j': 2}
{'i': 2, 'j': 1}
{'i': 2, 'j': 2}
{'i': 3, 'j': 1}
{'i': 3, 'j': 2}
{'i': 4, 'j': 1}
{'i': 4, 'j': 2}
{'i': 5, 'j': 1}
{'i': 5, 'j': 2}
The reason is that I want to iterate over them. But because the whole space is too big, I do not want to generate all of them, store them and then iterate over that list of dictionaries. I thought about using the following recursive procedure, but I need some help with the yield
part. Where should it be? How do I avoid nested generators?
def iteration(conditions, currentCondition, valuedIndices):
if currentCondition == len(conditions):
yield valuedIndices
else:
cond = conditions[currentCondition]
index = cond[0]
lim1 = cond[1][0]
lim2 = cond[1][1]
for ix in range(lim1, lim2 + 1):
valuedIndices[index] = ix
yield iteration(conditions, currentCondition + 1, valuedIndices)
Now I would like to be able to do:
for valued_indices in iteration(conditions, 0, {}):
...
yield
withyield from
in the very last line of your function. – Eulau