如何制作多个以深度为参数的嵌套循环。 我正在考虑一个将深度作为参数的函数
def make_nested_loops(depth):
...
depth=3
的结果如下
for i1 in range(10):
for i2 in range(i1 + 1, 10):
for i3 in range(i2 + 1, 10):
# do stuff
到目前为止,我已经能够使用字符串构建和 exec
命令来完成此操作。但我认为有更好、更有效的方法来做到这一点。
最佳答案
一种低效但简单的方法是使用 itertools.product
并过滤不需要的元组:
def make_tuples(depth, n):
for i in itertools.product(range(n), repeat=depth):
if sorted(i) < i:
continue
yield i
更高效的是递归生成器:
def make_tuples(depth, n, start=0):
if depth == 0:
yield ()
else:
for x in range(start, n):
for t in make_tuples(depth - 1, n, x + 1):
yield (x,) + t
使用它看起来像
for (i1, i2, i3) in make_tuples(3, 10):
# do stuff with i1, i2, i3
如果深度确实是动态的,您当然不能解压来自make_tuples
的元组。 body 必须知道如何处理元组
固定但未知长度。
for tpl in make_tuples(n, 10):
# Do stuff with tpl
关于python - python中带有深度参数的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44972189/