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

2024-03-28 08:48:39 发布

您现在位置: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 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)

这个问题已经部分解决了,但是在如何更改range参数方面仍然有问题,比如上面的例子。 请原谅我弄得一团糟!:)


Tags: 代码infromimport程序算法for数量
2条回答

^{}已经可以准确地完成您想要的任务,只需将多个iterable(在本例中是您想要的范围)传递给它即可。它将从每个传递的iterable中收集一个元素。例如:

for a,b,c in product(range(2), range(3), range(4)):
    print (a,b,c)

输出

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)

如果您有大量的输入iterables。你知道吗


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

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)

你在找这样的东西吗?你知道吗

# 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
...

相关问题 更多 >