Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样用 flags 判断数组是否连续、可写?

查看完整题解

参考回答

直接回答

看 a.flags.c_contiguous 和 a.flags.f_contiguous 判断两种连续性。还可查 writeable 与 owndata。联合读取 shape 和 strides,更容易看出为什么是这个结果。

讲清原理

一维或带某些长度为一的轴时,两个连续性标志可以都真。像隔列切片,两者也可能都假。标志不能单独说明和另一个具体数组是否重叠,判断共享另用 shares_memory。

例子与易错点

下方从两个连续数组取相同的步长,再检查隔列切片的连续性。

import numpy as np

row_order = np.zeros((3, 4), dtype=np.int32, order="C")
col_order = np.zeros((3, 4), dtype=np.int32, order="F")
assert row_order.flags.c_contiguous and col_order.flags.f_contiguous
for source in (row_order, col_order):
    spaced = source[:, ::2]
    assert not spaced.flags.c_contiguous
    assert not spaced.flags.f_contiguous
    assert np.shares_memory(source, spaced)
print(row_order.strides, col_order.strides)

相关题:第 78 题、第 79 题、第 82 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。