怎样用 flags 判断数组是否连续、可写?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
看 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)
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。