Python嵌套循环成语 [英] Python nested looping Idiom

查看:105
本文介绍了Python嵌套循环成语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 对于范围(x_size)中的x:
对于范围中的y (y_size):
for z(z_size):
pass#在这里做某事

Python中有更简洁的方法吗?我正在考虑沿着

 的方向行事,对于x,z,y in ...? :


解决方案

您可以使用 itertools.product

 >>>对于itertools.product(范围(2),范围(2),范围(3))中的x,y,z:
...打印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


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

解决方案

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

这篇关于Python嵌套循环成语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆