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

如何修改numpy循环抽样代码 实现带分组编号的格式化输出

代码修改方案

原逻辑的问题是循环遍历数组行时,没有同步生成分组序号,只需要给遍历过程增加从1开始的计数,格式化输出内容即可,不需要改动原有随机抽样的逻辑,保证抽样结果和预期一致。
完整可运行修改后代码如下:

import numpy as np

m = np.array([[7, 0, 0, 6],
              [5, 6, 6, 1],
              [4, 1, 6, 7],
              [5, 3, 4, 7]])

np.random.seed(55)
# enumerate第二个参数设置序号起始值为1
for idx, row in enumerate(m, 1):
    res = np.random.choice(row, 2, replace=False)
    print(f"Group {idx}: {res}")

运行上述代码,将输出符合要求的格式结果:

Group 1: [7 6]
Group 2: [1 6]
Group 3: [4 6]
Group 4: [4 5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:01:07