Python nested looping Idiom

别说谁变了你拦得住时间么 提交于 2019-11-27 04:30:21

You can use itertools.product:

>>> for x,y,z in itertools.product(range(2), range(2), range(3)):
...     print x,y,z
... 
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2

If you've got numpy as a dependency already, numpy.ndindex will do the trick ...

>>> for x,y,z in np.ndindex(2,2,2):
...     print x,y,z
... 
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

Use itertools.product():

import itertools
for x, y, z in itertools.product(range(x_size), range(y_size), range(z_size)):
    pass # do something here

From the docs:

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression.
...

Jeanne Boyarsky

It depends on what is inside the loop. If dealing with lists, you may be able to use a list comprehension

For the more general case, see this post on itertools.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!