Python 嵌套循环习语 [英] Python nested looping Idiom
本文介绍了Python 嵌套循环习语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常发现自己这样做:
for x in range(x_size):对于范围内的 y(y_size):对于范围内的 z(z_size):pass # 在这里做点什么
在 Python 中是否有更简洁的方法来做到这一点?我正在考虑类似
for x, z, y in ... ?:
解决方案
您可以使用 itertools.product:
<预><代码>>>>对于 itertools.product(range(2), range(2), range(3)) 中的 x,y,z:... 打印 x,y,z...0 0 00 0 10 0 20 1 00 1 10 1 21 0 01 0 11 0 21 1 01 1 11 1 2I 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屋!
查看全文