Python nested looping Idiom

后端 未结 4 1448
北海茫月
北海茫月 2020-11-30 07:27

I often find myself doing this:

for x in range(x_size):
    for y in range(y_size):
        for z in range(z_size):
            pass # do something here


        
相关标签:
4条回答
  • 2020-11-30 08:04

    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.

    0 讨论(0)
  • 2020-11-30 08:12

    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
    
    0 讨论(0)
  • 2020-11-30 08:13

    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
    
    0 讨论(0)
  • 2020-11-30 08:21

    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.
    ...

    0 讨论(0)
提交回复
热议问题