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

如何为8×10二维数组A生成存储各元素行索引的二维数组?

生成存储二维数组元素行索引的新数组

Python 原生列表实现

直接通过列表推导式快速生成,无需依赖第三方库:

# 原数组A的行数和列数
rows = 8
cols = 10
# 生成行索引数组
row_index_array = [[i for _ in range(cols)] for i in range(rows)]

逻辑很简单:外层循环遍历每一行的索引i(从0到7),内层循环为当前行生成10个重复的i,最终组合成8×10的二维数组。

NumPy 高效实现

如果用NumPy处理大规模数组,这种方式更高效简洁:

import numpy as np

# 方法一:用repeat扩展列
row_index_array = np.arange(8).reshape(-1, 1).repeat(10, axis=1)

# 方法二:用tile复制行索引
row_index_array = np.tile(np.arange(8).reshape(-1, 1), (1, 10))

两种方法都是先生成0到7的行索引序列,转成列向量后,在水平方向扩展10次,得到目标数组。

Java 实现

通过双重循环初始化并赋值:

public class RowIndexGenerator {
    public static void main(String[] args) {
        int rows = 8;
        int cols = 10;
        int[][] rowIndexArray = new int[rows][cols];
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                rowIndexArray[i][j] = i;
            }
        }
    }
}

先创建指定大小的二维数组,然后遍历每一行,给该行所有元素赋值为当前行的索引i。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:40:45