Python嵌套for循环嵌套迭代器res

2024-09-25 08:39:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个数独解算器,其中一部分是抓取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值重新指定为三的最接近的倍数,然后迭代3x3框中的所有值。在

我知道内部for循环将col赋值为col+1,但我没想到的是,当row递增1时,col不会重置回其原始值(即col = col - (col % 3)处的值)

下面是上面代码中print语句的输出: 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) 您会注意到,当行增加1时,col将保持在内部循环结束时的值。有人能解释一下这里发生了什么吗?我原以为Python会放弃迭代的局部变量并重置,但可能我疯了@_@

另一方面,这段代码做了我想要的(但是我很惊讶这是需要的):

^{pr2}$

输出:

row, col values initially are (0, 2)
row, col is (0, 0)
row, col is (0, 1)
row, col is (0, 2)
row, col is (1, 0)
row, col is (1, 1)
row, col is (1, 2)
row, col is (2, 0)
row, col is (2, 1)
row, col is (2, 2)
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, 3)
row, col is (1, 4)
row, col is (1, 5)
row, col is (2, 3)
row, col is (2, 4)
row, col is (2, 5)

Tags: 代码inboardforisrangecolare
2条回答

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

Python没有块范围(例如在C或Java中);相反,变量的作用域是函数、类和模块。 在您的例子中,col的作用域是函数,因此没有“outer col variable”重置为它,它一直是同一个变量。在

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

相关问题 更多 >