Python 动态生成灵活数量的嵌套for循环

Python 动态生成灵活数量的嵌套for循环,python,for-loop,dynamic,Python,For Loop,Dynamic,是否可以根据输入的长度在函数中添加/减少嵌套for循环的数量 例如: 基于长度为3的特定输入,我可能需要使用1个嵌套for循环(for循环在另一个for循环中)。与此类似, 范围内的i(0,len(输入)+1): 对于范围内的j(i+1,len(输入)+1): 然而,当输入长度为4时,如果我能在已经存在的嵌套for循环中引入额外的for循环,我就可以得到我的结果,这意味着 范围内的i(0,len(输入)+1): 对于范围内的j(i+1,len(输入)+1): 对于范围内的k(j+1,len(输

是否可以根据输入的长度在函数中添加/减少嵌套for循环的数量

例如: 基于长度为3的特定输入,我可能需要使用1个嵌套for循环(for循环在另一个for循环中)。与此类似,

范围内的i(0,len(输入)+1):
对于范围内的j(i+1,len(输入)+1):
然而,当输入长度为4时,如果我能在已经存在的嵌套for循环中引入额外的for循环,我就可以得到我的结果,这意味着

范围内的i(0,len(输入)+1):
对于范围内的j(i+1,len(输入)+1):
对于范围内的k(j+1,len(输入)+1):`
类似地,如果输入长度是5,那么我想引入另一个for循环

范围内的i(0,len(输入)+1):
对于范围内的j(i+1,len(输入)+1):
对于范围内的k(j+1,len(输入)+1):
对于范围内的l(k+1,len(输入)+1):`
模式是,对于长度为n的输入,将有n-1个for循环

有没有可能在Python中创建这样的函数?

由此,用C编写并快速翻译成Python的代码为您提供了以下信息:

如果我们看看嵌套循环是如何工作的,我们会发现最内部的 循环在大多数情况下都有效,只有当我们 内部循环中的值已用完

要将其转换为动态嵌套循环,我们可以表示 数组中的不同循环变量。为了简单起见,我们假设 这些变量的上限是一个常数,如上所示 例如

为了实现动态嵌套循环,我们需要增加最内部的 循环变量,直到值用完为止。只有这样,我们才需要考虑 更改上层循环变量

当这段代码生成组合数学时,可以想象将其重新用于不同的目的

如评论中所述,这可能不是一个好的设计选择。
必须有一种更好(更具pythonic)的方法来使用生成器,或者可能是异步的,而不是增加间接寻址的级别

当然,也有递归,但这不是问题的重点

生成动态嵌套循环 输出:
听起来像个XY问题。你想解决的真正问题是什么?我们可以举个例子。如果应用得当,重现性适合这里。例如,我有一个数字/字母列表作为输入。Input=[1,2,3,4]我想创建所有单个元素的组合。与下列[1]、[2]、[3]、[4]、[1,2]、[1,3]、[1,4]、[2,3]、[2,4]、[3,4]、[1,2,4]、[1,3,4]、[2,3,4]、[1,2,3,4]类似,解决实际问题的方法可能不同。但在试图解决这个问题时,我提出了一个问题,即嵌套for循环的数量可变;这个问题是关于一个可变数量的for循环,而你链接的所谓dupe是关于代的组合。@ReblochonMasque好的,让问题打开。但将仅声明指向此的正确解决方案的链接:。构建数量可变的for循环是一个糟糕的设计。
MAXROWS = 4      #    contains the number of levels
MAXVALUES = 2    #    contains the maximum combination for a given nested variables.

display = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

arrs = [0] * MAXROWS   # represent the different variables in the for loops                      
status = False

while not status: 

    total = 0
    # calculate total for exit condition
    for r in range(MAXROWS):
        total += arrs[r]
        # test for exit condition
    if total == (MAXVALUES - 1) * MAXROWS:
        status = True

    # printing
    for r in range(MAXROWS):
        print(display[arrs[r]], end=' ')  # print(arrs[r])
    print()

    # increment loop variables
    change = True
    r = MAXROWS-1    # start from innermost loop

    while change and r >= 0:
    # increment the innermost variable and check if spill overs
        if (arrs[r] + 1) > MAXVALUES-1:    
            arrs[r] += 1
            arrs[r] = 0     #  // reintialize loop variable
            # Change the upper variable by one
            # We need to increment the immediate upper level loop by one
            change = True   
        else:
            arrs[r] += 1
            change = False   # Stop as there the upper levels of the loop are unaffected

            # We can perform any inner loop calculation here arrs[r]

        r -= 1  #  move to upper level of the loop
1 1 1 1 
1 1 1 2 
1 1 2 1 
1 1 2 2 
1 2 1 1 
1 2 1 2 
1 2 2 1 
1 2 2 2 
2 1 1 1 
2 1 1 2 
2 1 2 1 
2 1 2 2 
2 2 1 1 
2 2 1 2 
2 2 2 1 
2 2 2 2