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

如何使用Numpy为数组添加行号并输出指定格式?

使用Numpy为数组添加行号并指定格式打印

假设你已有一个不带行号的Numpy数组,比如:

import numpy as np

# 原数组(4列数据)
original_arr = np.array([
    [39, 41, 43],
    [38, 32, 18],
    [27, 14, 17],
    [22, 21, 22],
    [20, 28, 23]
])

步骤1:生成行号列并拼接

通过np.arange生成从1开始的行号,转成列向量后,用np.hstack和原数组横向拼接:

# 生成行号列(形状匹配原数组行数)
row_numbers = np.arange(1, original_arr.shape[0]+1).reshape(-1, 1)
# 拼接行号和原数组
arr_with_rows = np.hstack([row_numbers, original_arr])

步骤2:按指定格式打印

循环遍历拼接后的数组,每行格式化输出成你要的样式:

for row in arr_with_rows:
    # 先把行元素转成字符串并拼接,再套入格式
    row_str = ", ".join(map(str, row))
    print(f"               [{row_str}],")

运行后就能得到目标输出:

[1, 39, 41, 43],
               [2, 38, 32, 18],
               [3, 27, 14, 17],
               [4, 22, 21, 22],
               [5, 20, 28, 23]

这种写法适配任意列数的原数组,不用硬编码格式参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:55:19