How To Traverse A High-order Range In Python?
In python, we can use range(x) to traverse from 0 to x-1. But what if I want to traverse a high-order range? For example, given (a, b), I want to traverse all (x1, x2) such that 0
Solution 1:
Use itertools.product:
from itertools import product
for x, y, z in product(range(a), range(b), range(c)):
print( (x,y,z) )
With a variable number of dimensions:
limits = [5, 3, 7, 6]
for v in product(*(range(n) for n in limits)):
print(v)
Post a Comment for "How To Traverse A High-order Range In Python?"