python 中具有深度参数的嵌套循环
Nested loops with depth parameter in python
如何制作多个以深度为参数的嵌套循环。
我正在考虑一个将深度作为参数的函数
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
命令来完成此操作。但我认为有更好更有效的方法。
我认为最多可以有 21 个嵌套循环。所以你可以做的是在你的函数中有 21 个嵌套循环,并检查每个循环是否达到了所需的深度。如果不是,则将当前深度变量加一。
一种低效但简单的方法是使用 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
如何制作多个以深度为参数的嵌套循环。 我正在考虑一个将深度作为参数的函数
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
命令来完成此操作。但我认为有更好更有效的方法。
我认为最多可以有 21 个嵌套循环。所以你可以做的是在你的函数中有 21 个嵌套循环,并检查每个循环是否达到了所需的深度。如果不是,则将当前深度变量加一。
一种低效但简单的方法是使用 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