python For循环无明显原因中断

pgky5nke  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(180)

如果我运行下面的代码,我得到i = 42598。

import numpy as np
all_sets = []
working_sets = []

numbers = np.arange(10)
operators = ['+', '-', '*', '/']

i = 0
expression = ['', '', '', '', '', '', '']
for n1 in numbers:
    expression[0] = str(n1)
    for o1 in operators:
        expression[1] = o1
        for n2 in numbers:
            expression[2] = str(n2)
            for o2 in operators:
                expression[3] = o2
                for n3 in numbers:
                    expression[4] = str(n3)
                    for o3 in operators:
                        expression[5] = o3
                        for n4 in numbers:
                            expression[6] = str(n4)
                            i += 1

                            # get all sets for comparison
                            numbers = sorted([expression[0], expression[2], expression[4], expression[6]])
                            if not (numbers in all_sets):
                                all_sets.append(numbers)

print(i)

但是如果我注解掉这一点

# get all sets for comparison
numbers = sorted([expression[0], expression[2], expression[4], expression[6]])
if not (numbers in all_sets):
    all_sets.append(numbers)

我得到i = 640000,为什么?是什么破坏了我的for循环?

waxmsbnn

waxmsbnn1#

您的numbers数组开始时包含10个元素,但在某个时刻,执行将到达您将其更改为仅包含4个值的位置(numbers = sorted([expression[0], expression[2], expression[4], expression[6]]))。从那时起,所有最初要运行10次的数字循环都将缩短为4次。这可能会给予人一种发生中断的印象,但实际上循环刚刚到达(新)数组的结尾。

相关问题