Python中具有可变范围和可变循环数的多个for循环

Python中具有可变范围和可变循环数的多个for循环,python,Python,使用此代码: from itertools import product for a, b, c, d in product(range(low, high), repeat=4): print (a, b, c, d) 我有这样一个输出: 0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 1 1 0 0 1 2 0 0 2 0 0 0 2 1 0 0 2 2 但我如何才能创建一个能够做到这一点的算法: 0 0 0 0 0 0 0 1 0 0 0 2 0 0

使用此代码:

from itertools import product

for a, b, c, d in product(range(low, high), repeat=4):
    print (a, b, c, d)
我有这样一个输出:

0 0 0 0
0 0 0 1
0 0 0 2
0 0 1 0
0 0 1 1
0 0 1 2
0 0 2 0
0 0 2 1
0 0 2 2
但我如何才能创建一个能够做到这一点的算法:

0 0 0 0
0 0 0 1
0 0 0 2
0 0 0 3
0 0 0 4
0 0 1 1
0 0 1 2
0 0 1 3
0 0 1 4
0 0 2 2
0 0 2 3
0 0 2 4
0 0 3 3
0 0 3 4
0 0 4 4
更重要的是:输出的每一列必须具有不同的范围,例如:第一列:0-4第二列:0-10等。 列(a,b,c,d)的数量不是固定的;根据程序的其他部分,可以在2到200之间

更新:更容易理解和清楚

我需要的是这样的东西:

for a in range (0,10):
    for b in range (a,10):
        for c in range (b,10):
             for d in range (c,10):
                 print(a,b,c,d)
该问题已部分解决,但仍存在如何更改
范围
参数的问题,如上述示例。
请原谅我弄得一团糟!:)

你在找这样的东西吗

# the program would modify these variables below
column1_max = 2
column2_max = 3
column3_max = 4
column4_max = 5

# now generate the list
for a in range(column1_max+1):
    for b in range(column2_max+1):
        for c in range(column3_max+1):
            for d in range(column4_max+1):
                if c>d or b>c or a>b:
                    pass
                else:
                    print a,b,c,d
输出:

0 0 0 0
0 0 0 1
0 0 0 2
0 0 0 3
0 0 0 4
0 0 0 5
0 0 1 1
0 0 1 2
0 0 1 3
0 0 1 4
0 0 1 5
0 0 2 2
0 0 2 3
0 0 2 4
0 0 2 5
0 0 3 3
0 0 3 4
0 0 3 5
0 0 4 4
0 0 4 5
0 1 1 1
0 1 1 2
...
只需将多个iterables(在本例中是您想要的范围)传递给它,就可以完全完成您想要的任务。它将从每个传递的iterable中收集一个元素。例如:

for a,b,c in product(range(2), range(3), range(4)):
    print (a,b,c)
for elements in product(*(range(i) for i in [10,10,10,10])):
    if all(elements[i] <= elements[i+1] for i in range(len(elements)-1)):
        print(*elements)
输出

0 0 0
0 0 1
0 0 2
0 0 3
0 1 0
0 1 1
0 1 2
0 1 3
0 2 0
0 2 1
0 2 2
0 2 3
1 0 0
1 0 1
1 0 2
1 0 3
1 1 0
1 1 1
1 1 2
1 1 3
1 2 0
1 2 1
1 2 2
1 2 3
如果您的输入范围是可变的,只需将循环放在函数中,并使用不同的参数调用它即可。你也可以使用类似于

for elements in product(*(range(i) for i in [1,2,3,4])):
    print(*elements)
如果您有大量的输入可编辑项


随着您对变量范围的更新请求,使用
itertools.product
的一种很好的短路方法就不那么清晰了,尽管您总是可以检查每个iterable是否按升序排序(因为这基本上是您的变量范围所确保的)。根据你的例子:

for a,b,c in product(range(2), range(3), range(4)):
    print (a,b,c)
for elements in product(*(range(i) for i in [10,10,10,10])):
    if all(elements[i] <= elements[i+1] for i in range(len(elements)-1)):
        print(*elements)
用于产品中的元素(*[10,10,10,10]中i的范围(i)):

如果全部(元素[i]我不清楚您在这里想要什么。您的示例所需的输出是否就是您在这种情况下所需的全部输出?如果是,这是否需要仅使用
0
的两个填充值和
产品(范围(5),重复=2)
?如果您阅读itertools.product的文档,您会发现它可以使用多个iterables并完全按照您的要求进行操作。该示例只是一个简单的示例。我需要一个创建“n”列的算法(“n”是可变的,取决于程序的其他计算)。每个列必须在可变范围(0-10、5-9、2、23等)内迭代范围必须改变,如上面的例子。顺便问一下,你是否意识到200列,即使只有范围(2),也会给你2**200的可能性?(对于那些想知道的人来说,这是一个61位数字)例如,.200不是程序中使用的数字是的,但a、b、c、d是固定的。假设我的程序需要更改它;一次它们只有4,另一次它们可以是10,或者另一个数字正确,那么程序将修改列max变量,对吗?在您的示例中,您定义了a、b、c、d。并使用它创建4“for”但在我的程序中,“for”循环的数量是可变的,而不是固定的。