gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:10 25 4
gpt4 key购买 nike

我有一个 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

有什么我可以做的让它看起来更好一点吗?

最佳答案

您可以使用 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 。如果没有,您可能会丢失添加它的行:

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

关于python - 如何摆脱多个嵌套的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8899893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com