python - 是否可以将 "zip()"与步骤参数一起使用?

标签 python matrix multidimensional-array iterator

我想使用 zip() 方法在 Python 中提取二维数组的一个非常具体的部分(并避免困惑的 for 循环逻辑)。我想使用 zip 来实现这样的目的:

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

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

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

我正在 Python 中使用下面的二维数组来解决面试练习问题。

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

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

enter image description here

我知道我可以对网格进行子集化以获得前三行,如下所示:

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

我稍微修改了打印以使其明显,但在这一点上,我想使用 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 )

非常感谢任何帮助。谢谢。

最佳答案

没有 zipper 但是 [row[:3] for row in grid[:3]]

关于python - 是否可以将 "zip()"与步骤参数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748681/

相关文章:

python - IPython 使用与 shell 不同的 $PATH 环境

python 包装

c++ - 如何在 opencv c++ 中为不同的 Matrix 类型编写方法而不明确指定 Mat 类型

OpenGL glRotate 和 glTranslate 顺序

c++ - 我如何创建一堆多维数组

php - 将字符串分解为二维数组

c - 为什么在初始化多维数组时不能完全省略维度?

在 Windows 中运行的 Python 代码,我可以使用 "if not win32"绕过它的一部分吗

python - 将元素列表组合成元组列表

c++ - 使用 Eigen3 求无矩阵算子的特征值