How can I get rid of multiple nested for loops?

妖精的绣舞 提交于 2019-12-02 06:45:47

问题


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?


回答1:


You can use itertools to simplify your code:

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)

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)

The lines in your code

else:
    pass

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




回答2:


You can use something along the lines of:

for x, y, z in product(range(0,p), range(0,p), range(0,p)):
    print(x,y,z)

or

for x, y, z in product(range(0,p), repeat=3):
    print(x,y,z)

For python2.7 you need to from itertools import product.



来源:https://stackoverflow.com/questions/8899893/how-can-i-get-rid-of-multiple-nested-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!