具有itertools.product的嵌套循环仅运行1次

问题描述 投票:-2回答:2

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

这里是代码:

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]

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

python itertools
2个回答
1
投票

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


0
投票

oper = list(oper)在循环的第一次运行中已结束,在第二次运行中没有任何迭代可做。如果仅在循环中重新定义oper,就可以了。

oper
© www.soinside.com 2019 - 2024. All rights reserved.