首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python嵌套for循环嵌套迭代器重置

Python嵌套for循环嵌套迭代器重置
EN

Stack Overflow用户
提问于 2018-07-29 01:30:28
回答 2查看 729关注 0票数 0

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

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

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

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

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

输出:

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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-29 01:44:56

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

票数 0
EN

Stack Overflow用户

发布于 2018-07-29 01:45:08

Python没有块作用域(例如在C或Java中);相反,变量的作用域是函数、类和模块。在你的例子中,col的作用域是函数,所以没有‘外部col变量’可以重置,它一直都是同一个变量。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51573711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档