循环的部分嵌套

时间:2015-04-12 19:23:01

标签: python loops for-loop recursion nested

注意:更正的问题!

众所周知,itertools可以轻松创建嵌套for 使用itertools.product循环。但以下是我想要的,也不能做到的。使用

lfl = int(input( "length of first loop: "))
nol = int(input( "number of loops: "))

可造成:

  • 循环长度:12
  • 循环次数:4

我想要一个等价物:

for i1 in range(1,12):
    for i2 in range(i1,12):
        for i3 in range(i2,12):
            for i4 in range(i3,12):
                function(i1,i2,i3,i4)

itertools.product对许多人有所帮助。

或者nol导致创建func_1(x),func_2(x,y),.... func_nol-1(x,y,...)和代码需要的更一般的问题相当于:

for i1 in range(1,12):
    for i2 in range(func_1(i1),12):
        for i3 in range(func_2(i1,i2),12):
            for i4 in range(func_3(i1,i2,i3),12):
                function(i1,i2,i3,i4)

还有一个进一步的概括

for i1 in range(1,12):
    for i2 in range(start_func_1(i1, *global),end_func_(12, *global)):
        for i3 in range(start_func_2(i1,i2,*global),end_func_2(12,*global):
            for i4 in range(start_func_3  etc....

3 个答案:

答案 0 :(得分:1)

对于已更正的问题,请在范围列表中尝试combinations_with_replacement而不是product

from itertools import combinations_with_replacement

nums = [10, 11, 12, 13]
for c in combinations_with_replacement(nums, 3):
    print c

打印

(10, 10, 10)
(10, 10, 11)
(10, 10, 12)
(10, 10, 13)
(10, 11, 11)
(10, 11, 12)
(10, 11, 13)
(10, 12, 12) 
...

答案 1 :(得分:0)

您可以使用product执行此操作 - 您只需在初始准备步骤中创建循环的“维度”:

from itertools import product

length = 12
loops = 4

ranges = [range(x+1,length) for x in range(loops)]

def f(x):  # accepts a tuple, since the number of arguments may vary
    print("f(%s)" % repr(x))

for t in product(*ranges):
    f(t)

答案 2 :(得分:0)

这与您提供的代码完全相同:

from itertools import product

lfl = 12
nol = 4

ranges = (range(i, lfl) for i in range(1, nol + 1))
args = product(*ranges)

for arg in args:
    function(*arg)

它使用generator expression构建用于循环传递给itertools.productargument list unpacking的范围列表,以将单个参数元组作为函数/的单独参数传递给product()

演示:

from itertools import product

def function(*args):
    return args

results_nested = []
results_product = []

for i1 in range(1, 12):
    for i2 in range(2, 12):
        for i3 in range(3, 12):
            for i4 in range(4, 12):
                results_nested.append(function(i1, i2, i3, i4))

lfl = 12
nol = 4

ranges = (range(i, lfl) for i in range(1, nol + 1))
args = product(*ranges)

for arg in args:
    results_product.append(function(*arg))


assert results_nested == results_product