2

我有一个数独板作为这个列表,

board = [   ['.', 2, '.', '.', '.', 4, 3, '.', '.'], 
            [9, '.', '.', '.', 2, '.', '.', '.', 8], 
            ['.', '.', '.', 6, '.', 9, '.', 5, '.'], 
            ['.', '.', '.', '.', '.', '.', '.', '.', 1], 
            ['.', 7, 2, 5, '.', 3, 6, 8, '.'], 
            [6, '.', '.', '.', '.', '.', '.', '.', '.'], 
            ['.', 8, '.', 2, '.', 5, '.', '.', '.'], 
            [1, '.', '.', '.', 9, '.', '.', '.', 3], 
            ['.', '.', 9, 8, '.', '.', '.', 6, '.']    ]

我可以很容易地检查某个值是否存在于一行中,或者不是那么容易, value in board[row][:]但我不能对列做同样的事情。例如,当我编写value in board[:][col] 它时,它会以某种方式选择row, 以该值作为索引,col然后尝试找到指定的value.

例如,print(board[6][:])给出['.', 8, '.', 2, '.', 5, '.', '.', '.']第 7 行)和print(board[:][2])给出['.', '.', '.', 6, '.', 9, '.', 5, '.']第 3 行)。我真的很困惑为什么会这样。

我的问题是,对于列是否有等效的语法board[row][:]?更重要的是为什么board[:][col]不起作用?

4

3 回答 3

4

等效语法是zip(*board)[2][:]

>>> zip(*board)[2][:]
('.', '.', '.', '.', 2, '.', '.', '.', 9)
>>> 2 in zip(*board)[2][:]
True

参阅zip().

您的方法不起作用,因为board[:]意味着“所有行”,即与board. 所以board[:][2]等价于board[2]。你也不需要这个[:]部分value in board[row][:]

需要明确的是,正如@VPfB 所提到的,该[:]语法通常用于复制。由于您只是在阅读列表,因此没关系(实际上效率略低,因为您正在创建整个板的内存副本)。

于 2019-10-28T06:37:21.540 回答
0

如果您使用 NumPy,您可以轻松访问列值。

>> board = numpy.array([
    [".", 2, ".", ".", ".", 4, 3, ".", "."],
    [9, ".", ".", ".", 2, ".", ".", ".", 8],
    [".", ".", ".", 6, ".", 9, ".", 5, "."],
    [".", ".", ".", ".", ".", ".", ".", ".", 1],
    [".", 7, 2, 5, ".", 3, 6, 8, "."],
    [6, ".", ".", ".", ".", ".", ".", ".", "."],
    [".", 8, ".", 2, ".", 5, ".", ".", "."],
    [1, ".", ".", ".", 9, ".", ".", ".", 3],
    [".", ".", 9, 8, ".", ".", ".", 6, "."],
])

>> board[:,0]
>> array([".", 9, ".",".",".",6,".",1,"."])
于 2019-10-28T06:44:25.253 回答
0

您对索引在 Python 中的工作方式感到困惑。这可能会澄清一点:

board = [
    [".", 2, ".", ".", ".", 4, 3, ".", "."],
    [9, ".", ".", ".", 2, ".", ".", ".", 8],
    [".", ".", ".", 6, ".", 9, ".", 5, "."],
    [".", ".", ".", ".", ".", ".", ".", ".", 1],
    [".", 7, 2, 5, ".", 3, 6, 8, "."],
    [6, ".", ".", ".", ".", ".", ".", ".", "."],
    [".", 8, ".", 2, ".", 5, ".", ".", "."],
    [1, ".", ".", ".", 9, ".", ".", ".", 3],
    [".", ".", 9, 8, ".", ".", ".", 6, "."],
]

first = board[0]
second = board[0][0]

# Prints the row, as expected.
print(first)  # ['.', 2, '.', '.', '.', 4, 3, '.', '.']

# Prints the value of the INDEX in the row[0].
print(second)  # .

# Finds the actual column values by iterating through the values in index 0 of all the rows.
column = []
for row in board:
    column.append(row[0])  # Row number 0.

print(column) # ['.', 9, '.', '.', '.', 6, '.', 1, '.']
于 2019-10-28T06:39:35.333 回答