Pythonic way to iterate through multidimensional space?
Peter Otten
__peter__ at web.de
Tue Aug 5 16:48:10 EDT 2014
Frank Miles wrote:
> I need to evaluate a complicated function over a multidimensional space
> as part of an optimization problem. This is a somewhat general problem
> in which the number of dimensions and the function being evaluated can
> vary from problem to problem.
>
> I've got a working version (with loads of conditionals, and it only works
> to #dimensions <= 10), but I'd like something simpler and clearer and
> less hard-coded.
>
> I've web-searched for some plausible method, but haven't found anything
> "nice". Any recommendations where I should look, or what technique should
> be used?
Not sure this is what you want, but if you have nested for loops -- these
can be replaced with itertools.product():
>>> a = [1, 2]
>>> b = [10, 20, 30]
>>> c = [100]
>>> for x in a:
... for y in b:
... for z in c:
... print(x, y, z)
...
1 10 100
1 20 100
1 30 100
2 10 100
2 20 100
2 30 100
>>> for xyz in product(a, b, c):
... print(*xyz)
...
1 10 100
1 20 100
1 30 100
2 10 100
2 20 100
2 30 100
More information about the Python-list
mailing list