如何摆脱多个嵌套的for循环? [英] How can I get rid of multiple nested for loops?
问题描述
我有一个Python(3.2)脚本,用于搜索具有所需属性的点.但是它有这个丑陋的部分:
I have a Python (3.2) script that searches for points with a property that I want. But it has this ugly part:
for x in range(0,p):
for y in range(0,p):
for z in range(0,p):
for s in range(0,p):
for t in range(0,p):
for w in range(0,p):
for u in range(0,p):
if isagoodpoint(x,y,z,s,t,w,u,p):
print(x,y,z,s,t,w,u)
else:
pass
我可以做些什么让它看起来好一点吗?
Is there something I can do so that it looks a bit better?
推荐答案
您可以使用 itertools 简化代码:
from itertools import product
def print_good_points(p, dimensions=7):
for coords in product(range(p), repeat=dimensions):
args = coords + (p,)
if isagoodpoint(*args):
print(*coords)
可以解决您所说的问题;但是,我不确定您是否真的想在isagoodpoint()
的参数中包括p
.如果没有,您可能会丢失添加它的行:
That solves your problem as stated; however, I'm not sure that you really wanted to include p
in the arguments to isagoodpoint()
. If not, you can lose the line that adds it:
from itertools import product
def print_good_points(p, dimensions=7):
for coords in product(range(p), repeat=dimensions):
if isagoodpoint(*coords):
print(*coords)
代码中的行
else:
pass
顺便说一句,
什么也不做.另外,range(0, p)
等同于range(p)
.
do nothing, by the way. Also, range(0, p)
is equivalent to range(p)
.
还有...以防万一您在函数调用中对*
的使用不熟悉:
And ... just in case this use of *
in function calls is unfamiliar to you:
http://docs.python.org/3.2/reference/expressions.html#index-34
这篇关于如何摆脱多个嵌套的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!