python – 是否可以使用带有步骤参数的“zip()”?

我想使用zip()方法在
Python中提取2D数组的一个非常特定的部分(并避免凌乱的循环逻辑).我想使用zip来实现这样的目标:

>>> sub_matrix = list(zip([*grid[0:3]]*3))

# Desired output example (Option 1)
[".","4",".", ".",".","4",".",".","."]

# Desired output example (Option 2)
[[".","4","."],  
[".",".","4"],
[".",".","."]]

我正在使用Python下面的2D数组处理面试实践问题.

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

解决问题的一部分涉及确保数独游戏中的每个3 x 3“区域”包含合法值.我想用zip()快速提取矩阵的3 x 3部分.例如,左上角区域会导致测试失败,因为它包含4次两次.

《python – 是否可以使用带有步骤参数的“zip()”?》

我知道我可以将网格子集化为前三行,如下所示:

    >>> sub_grid = grid[0:3]
    >>> print(sub_grid)
    [['.', '4', '.', '.', '.', '.', '.', '.', '.'], 
    ['.', '.', '4', '.', '.', '.', '.', '.', '.'], 
    ['.', '.', '.', '1', '.', '.', '7', '.', '.']]

我稍微修改了一下打印以使其显而易见,但此时,我想使用’step’为3来压缩三个数组,这样每个新数组将从每个数组中压缩3个值,然后再继续下一个.

Python3 docs on zip中有一个关于我如何认为可以做到这一点的摘录,但我无法获得所需的输出.

The left-to-right evaluation order of the iterables is guaranteed.
This makes possible an idiom for clustering a data series into
n-length groups using zip(*[iter(s)]*n).

(对于子孙后代,问题来自CodeFights will be hidden until unlocked)

任何帮助是极大的赞赏.谢谢.

最佳答案 没有拉链但是

[行[:3]表示网格中的行[:3]]

点赞