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

Python中如何基于相邻值差值阈值对一维数组动态分组并求各组均值

实现方案

核心思路

  • 首先对原数组做升序排序,保证相邻元素的差值判断逻辑有效
  • 遍历排序后的数组,按照「当前元素与当前组最后一个元素的差值≤阈值则归为同一组,否则新建分组」的规则完成分组
  • 对每个分组计算平均值,按需求保留小数位数即可

代码实现

原生Python实现(无需第三方依赖)

def calc_group_mean(arr, threshold=1, decimal_places=3):
    if not arr:
        return []
    # 先排序保证相邻差值判断有效,若输入本身已排序可删除此行
    sorted_arr = sorted(arr)
    groups = [[sorted_arr[0]]]
    for num in sorted_arr[1:]:
        if num - groups[-1][-1] <= threshold:
            groups[-1].append(num)
        else:
            groups.append([num])
    # 计算每组均值,保留指定小数位
    return [round(sum(group)/len(group), decimal_places) for group in groups]

# 测试用例
B = [8.55905955, 8.63646974, 21.7694643, 21.87843119, 21.92463355]
B_new = calc_group_mean(B)
print(B_new) # 输出 [8.598, 21.858]

Numpy实现(适合处理大规模数组)

import numpy as np

def calc_group_mean_np(arr, threshold=1, decimal_places=3):
    if len(arr) == 0:
        return []
    # 先排序保证相邻差值判断有效,若输入本身已排序可删除此行
    sorted_arr = np.sort(arr)
    # 找到差值超过阈值的分割位置
    split_points = np.where(np.diff(sorted_arr) > threshold)[0] + 1
    # 分割数组
    groups = np.split(sorted_arr, split_points)
    # 计算每组均值
    return [np.round(np.mean(group), decimal_places) for group in groups]

# 测试用例
B = [8.55905955, 8.63646974, 21.7694643, 21.87843119, 21.92463355]
B_new = calc_group_mean_np(B)
print(B_new) # 输出 [8.598, 21.858]

参数说明

  • arr:输入的一维数组,长度任意,支持空数组输入
  • threshold:分组阈值,可根据需求自定义调整,示例中用的是1
  • decimal_places:均值保留的小数位数,示例中为3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:15:02