Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

loops - Python nested looping Idiom

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

Is there a more concise way to do this in Python? I am thinking of something along the lines of

for x, z, y in ... ? :
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...