嵌套的Python用于循环嵌套的迭代器重置

时间:2018-07-28 17:30:28

标签: python loops for-loop

我正在编写一个数独求解器,其中一个是在3x3子框中获取值。我的代码如下:

def taken_numbers_in_box(row, col, board):
    col = col - (col % 3)
    row = row - (row % 3)
    print('row, col values initially are', (row, col))
    taken_numbers = set()
    for row in range(row, row + 3):
        for col in range(col, col + 3):
            print('row, col is', (row, col))
            taken_numbers.add(board[row][col])

    return taken_numbers

我将col值重新分配为三的最接近的倍数,然后遍历3 x 3框中的所有值。

我知道内部for循环将col分配为col + 1,但是我没想到的是,当行增加1时,col不会重置回其原始值(即{ {1}})

以下是上面代码中print语句的输出: col = col - (col % 3) 您会注意到,当行增加1时,col保持在内部循环结束处的值。有人可以解释这里发生了什么吗?我以为Python会舍弃迭代中的局部变量并重置,但是也许我发疯了 row, col values initially are (0, 0) row, col is (0, 0) row, col is (0, 1) row, col is (0, 2) row, col is (1, 2) row, col is (1, 3) row, col is (1, 4) row, col is (2, 4) row, col is (2, 5) row, col is (2, 6) row, col values initially are (0, 3) row, col is (0, 3) row, col is (0, 4) row, col is (0, 5) row, col is (1, 5) row, col is (1, 6) row, col is (1, 7) row, col is (2, 7) row, col is (2, 8) row, col is (2, 9)

另一方面,这段代码确实可以满足我的要求(但我很惊讶这是必需的):

@_@

输出:

def taken_numbers_in_box(row, col, board):
    col_initial = col - (col % 3)
    row = row - (row % 3)
    taken_numbers = set()
    print('row, col values initially are', (row, col))
    for row in range(row, row + 3):
        col = col_initial
        for col in range(col, col + 3):
            print('row, col is', (row, col))        
            taken_numbers.add(board[row][col])

    return taken_numbers

2 个答案:

答案 0 :(得分:1)

Python没有块范围(例如,在C或Java中);相反,变量的作用域是函数,类和模块。 在您的情况下,col的作用域是该函数,因此没有要重置为的“外部col变量”,它一直都是相同的变量。

有关更好的概述,请参见https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces

答案 1 :(得分:0)

您设置了for col in range (col, col+3)。 即使在本地不再使用col,python编译器仍保留其值。与Java或C ++中定义的变量作用域定义不同。因此,您应该将代码更改为 for col in range (initial_col, initial_col+3)