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

问题描述 投票:1回答: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

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

python python-3.x nested-loops python-3.2
2个回答
5
投票

您可以使用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


0
投票

您可以使用以下内容:

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

© www.soinside.com 2019 - 2024. All rights reserved.