You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将二维数组的行列索引映射到一维数组索引?

二维数组索引映射到一维数组的方法

对于方形二维数组,已知行索引 i 和列索引 j,要映射到一维数组的索引 idx,可以用以下公式:

idx = i * 列数 + j

其中“列数”是二维数组每行的元素个数(因为是方形数组,列数等于行数)。

示例验证

以你给出的例子为例:

  • 二维数组 mat 是2行2列的数组,列数为2
    import numpy as np
    mat = np.array([[6, 7], [8, 9]])
    arr = np.array([1, 2, 3, 4])
    
  • 映射计算:
    • mat[0,0]:0*2 + 0 = 0 → 对应 arr[0]
    • mat[0,1]:0*2 + 1 = 1 → 对应 arr[1]
    • mat[1,0]:1*2 + 0 = 2 → 对应 arr[2]
    • mat[1,1]:1*2 + 1 = 3 → 对应 arr[3]

如果需要批量转换或在numpy中直接操作,也可以用np.ravel_multi_index函数,传入行索引、列索引和数组形状即可得到一维索引:

# 比如获取mat[1,0]的一维索引
idx = np.ravel_multi_index((1, 0), mat.shape)
# idx的值为2,对应arr[2]

内容的提问来源于stack exchange,提问作者statwoman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:45:43