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

如何使用Numpy将数组按循环分配拆分为不等长3个子数组?

解决方案

你需要的是按循环索引分配的拆分方式,而np.array_split是将数组分割为连续的子块,因此不符合需求。以下是两种可行的numpy实现方式:

方法1:利用切片步长

直接通过起始索引+步长的切片语法,精准提取每组元素:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# 按循环规则拆分
group1 = arr[::3]   # 索引0,3,6,9 → 元素[1,4,7,10]
group2 = arr[1::3]  # 索引1,4,7 → 元素[2,5,8]
group3 = arr[2::3]  # 索引2,5,8 → 元素[3,6,9]

new_arrays = [group1, group2, group3]
print(new_arrays)

方法2:基于索引模运算(更通用)

如果需要适配任意分组数量(比如n组),可以通过索引的模运算来生成分组,扩展性更强:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
n_groups = 3

# 生成数组索引,按模n_groups分组
indices = np.arange(len(arr))
new_arrays = [arr[indices % n_groups == i] for i in range(n_groups)]

print(new_arrays)

输出结果

两种方法都会得到你需要的结果:

[array([ 1,  4,  7, 10]), array([2, 5, 8]), array([3, 6, 9])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:09:10