Dynamic For Loops In Python
Solution 1:
Use the itertools.product()
function to generate the values over a variable number of ranges:
forvaluesin product(*(range(*b) for b in boundaries_list)):
# do things with the values tuple, do_whatever(*values) perhaps
Don't try to set a variable number of variables; just iterate over the values
tuple or use indexing as needed.
Using *
in a call tells Python to take all elements of an iterable and apply them as separate arguments. So each b
in your boundaries_list
is applied to range()
as separate arguments, as if you called range(b[0], b[1], b[2])
.
The same applies to the product()
call; each range()
object the generator expression produces is passed to product()
as a separate argument. This way you can pass a dynamic number of range()
objects to that call.
Solution 2:
Just for fun, I thought that I would implement this using recursion to perhaps demonstrate the pythonic style. Of course, the most pythonic way would be to use the itertools
package as demonstrated by Martijn Pieters.
defdynamic_for_loop(boundaries, *vargs):
ifnot boundaries:
print(*vargs) # or whatever you want to do with the valueselse:
bounds = boundaries[0]
for i inrange(*bounds):
dynamic_for_loop(boundaries[1:], *(vargs + (i,)))
Now we can use it like so:
In [2]: boundaries = [[0,5,1], [0,3,1], [0,3,1]]
In [3]: dynamic_for_loop(boundaries)
000001002010011012020021022100101102110111112120121122200201202210211212220221222300301302310311312320321322400401402410411412420421422
Post a Comment for "Dynamic For Loops In Python"