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

如何将含非连续值的NumPy数组分割为连续值子集?

将NumPy数组分割为连续数值的子集

如何将如下所示的数组分割为n个子集,每个子集由连续数值组成?

import numpy as np
arr = np.array((0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 39, 40,
       41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))

你已经通过np.diff定位了分割点,但手动切片的方式无法灵活适配任意数量的连续子集。可以用np.split结合分割点实现自动分割:

通用实现代码

import numpy as np

arr = np.array((0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 39, 40,
       41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))

# 计算连续序列的分割点
cut_points = np.where(np.diff(arr) != 1)[0] + 1

# 自动分割为所有连续子集
continuous_subsets = np.split(arr, cut_points)

# 查看结果
for idx, subset in enumerate(continuous_subsets):
    print(f"连续子集 {idx+1}: {subset}")

代码说明

  • np.diff(arr):计算相邻元素的差值,差值不为1的位置就是连续序列的断点。
  • np.where(...) +1:将断点位置转换为原数组的分割索引(因为diff结果长度比原数组少1,需加1对齐)。
  • np.split(arr, cut_points):根据分割点自动拆分数组,返回所有连续数值的子数组列表。

运行输出:

连续子集 1: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
连续子集 2: [39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55]
连续子集 3: [66 67 68 69 70 71]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:15:44