python - python中带有深度参数的嵌套循环

标签 python loops nested-loops

如何制作多个以深度为参数的嵌套循环。 我正在考虑一个将深度作为参数的函数

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/

相关文章:

Javascript:嵌套for循环赋值

python - 即使在使用 .loc 之后,Pandas 仍然会收到 SettingWithCopyWarning

python - KVM api启动虚拟机

c - 不正确的循环 - CS50 Mario

python - 如何使用嵌套循环打印嵌套列表?

c - 用于定义和打印矩阵的所有元素的函数

Python:从列表中删除具有相同楼层函数的数字

python - 尝试检测圆心颜色时出错

linux - Bash脚本初学者问题: Looping,数组和字符检查

PHP如何循环遍历多个注释级别