python一堆数字相近的分成一组

复制代码
def group_nearest_numbers(numbers, threshold):
    groups = {}
    for num in numbers:
        found = False
        for group_id, group_members in groups.items():
            if abs(num - group_members[-1]) <= threshold:
                groups[group_id].append(num)
                found = True
                break
        if not found:
            groups[len(groups)] = [num]
    return groups.values()


# 示例使用
numbers = [1, 2, 3, 4, 500, 501, 502, 1000, 1001, 1002 ,1500,1600]
threshold = 100
groups = group_nearest_numbers(numbers, threshold)
for group in groups:
    print(group)

这个函数会将数字列表numbers中相差不超过threshold的数字分到同一组。最后,函数返回每个分组的列表。



这个时候 我修改了一下数字

打印结果是:


FR:徐海涛(hunkxu)

相关推荐
胡耀超1 分钟前
AI的记忆革命:从Titans架构到长时运行智能体,谷歌Google,Anthropic,NeurIPS 2025
人工智能·python·ai·架构·智能体·上下文·titans
川石课堂软件测试6 分钟前
使用loadrunner调用mysql API进行性能测试
服务器·数据库·python·selenium·mysql·单元测试·自动化
缘三水18 分钟前
【C语言】12.指针(2)
c语言·开发语言·指针
Python学习导航20 分钟前
Python开源项目月排行 2025年10月
开发语言·python
祝余Eleanor21 分钟前
Day 30 函数专题2 装饰器
人工智能·python·机器学习·数据分析
爱吃巧克力的程序媛22 分钟前
Qt 异步编程---概述
开发语言·qt
feifeigo12330 分钟前
MATLAB实现两组点云ICP配准
开发语言·算法·matlab
Yang-Never30 分钟前
Open GL ES->以指定点为中心缩放图片纹理的完整图解
android·java·开发语言·kotlin·android studio
fengfuyao98532 分钟前
粒子群算法(PSO)求解标准VRP问题的MATLAB实现
开发语言·算法·matlab
nwsuaf_huasir1 小时前
深度学习1.3-软件篇-2025Pycharm添加导入anaconda中虚拟环境的python解释器以及相关Error解决方案
人工智能·python·深度学习