如何摆脱多个嵌套的for循环?

ste*_*nos 1 python nested-loops python-3.x python-3.2

我有一个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
Run Code Online (Sandbox Code Playgroud)

我能做些什么让它看起来好一点吗?

Zer*_*eus 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)
Run Code Online (Sandbox Code Playgroud)

这解决了你所说的问题; 但是,我不知道,你真的想包括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)
Run Code Online (Sandbox Code Playgroud)

代码中的行

else:
    pass
Run Code Online (Sandbox Code Playgroud)

顺便说一句,什么都不做.而且,range(0, p)相当于range(p).

并且......以防万一*您在函数调用中的使用不熟悉:

http://docs.python.org/3.2/reference/expressions.html#index-34