使用itertools.product的嵌套循环仅运行1次

时间:2020-04-19 20:33:22

标签: python itertools

我在这里有点问题。我正在尝试创建一个嵌套循环,但是第二个循环只运行一次。

代码如下:

def solver(numbers, gleichung_list = [], temp = []):
    perm = itertools.permutations(numbers)
    permlist = [list(y) for y in perm]
    oper = itertools.product(['+', '-', '*', '/'], repeat=len(numbers)-1)
    for gleichung in permlist:
        print(gleichung)
        for ops in oper:
            print(ops)
            temp = [None] * (len(numbers)*2-1)
            temp[::2] = list(gleichung)
            temp[1::2] = list(ops)
            print(temp)
            print(ops)

    numbers = [1, 2]
    solver(numbers)

但是当我运行它时,这就是我得到的:

[1, 2]
('+',)
[1, '+', 2]
('+',)
('-',)
[1, '-', 2]
('-',)
('*',)
[1, '*', 2]
('*',)
('/',)
[1, '/', 2]
('/',)
[2, 1]

第二个循环为什么不运行?

2 个答案:

答案 0 :(得分:1)

product()函数返回一个迭代器而不是列表,因此您的嵌套循环在此迭代器上运行一次,因此不再有任何项。 在您的第一个循环之前添加oper = list(oper),以解决此问题。

答案 1 :(得分:0)

oper在循环的第一轮运行中已经结束,在第二轮运行中没有迭代的余地。如果您仅在循环中重新定义oper,那么就没问题了。

def solver(numbers, gleichung_list = [], temp = []):
    perm = itertools.permutations(numbers)
    permlist = [list(y) for y in perm]
    for gleichung in permlist:
        oper = itertools.product(['+', '-', '*', '/'], repeat=len(numbers)-1)
        print(gleichung)
        for ops in oper:
            print(ops)
            temp = [None] * (len(numbers)*2-1)
            temp[::2] = list(gleichung)
            temp[1::2] = list(ops)
            print(temp)
            print(ops)