如何去除多个嵌套的for循环?
我有一个用Python(3.2)写的脚本,它用来寻找我想要的某些特定点。但是有一部分看起来很糟糕:
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
有没有什么办法可以让它看起来好一点呢?
2 个回答
1
你可以使用类似下面的代码:
for x, y, z in product(range(0,p), range(0,p), range(0,p)):
print(x,y,z)
或者
for x, y, z in product(range(0,p), repeat=3):
print(x,y,z)
如果你在用 python2.7
,你需要先写 from itertools import product
。
6
你可以使用 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)
这样就解决了你提到的问题;不过,我不太确定你是否真的想把 p
放在 isagoodpoint()
的参数里。如果不想的话,可以去掉那一行加上它的代码:
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)
是一样的。
还有……如果你对在函数调用中使用 *
这个符号不太熟悉的话:
http://docs.python.org/3.2/reference/expressions.html#index-34