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)

相关推荐
2401_857918298 小时前
C++中的访问者模式实战
开发语言·c++·算法
格林威8 小时前
工业相机图像高速存储(C++版):RAID 0 NVMe SSD 阵列暴力提速,附海康实战代码!
开发语言·c++·人工智能·数码相机·计算机视觉·工业相机·堡盟相机
DamianGao8 小时前
MiniMax-M2.7 与 LangChain ToolStrategy 兼容性问题解决
python·langchain
elseif1238 小时前
CSP-S提高级大纲
开发语言·数据结构·c++·笔记·算法·大纲·考纲
兰.lan9 小时前
【黑马ai测试】Day01课堂笔记+课后作业
软件测试·笔记·python·ai·单元测试
国医中兴9 小时前
Python AI入门:从Hello World到图像分类
人工智能·python·分类
熊猫_豆豆9 小时前
Python 基于Dlib和OpenCV实现人脸融合算法+代码
图像处理·python·算法·人脸融合
波特率1152009 小时前
C++中类的const与static关键字修饰函数与变量辨析
开发语言·c++·
1941s9 小时前
Google Agent Development Kit (ADK) 指南 第六章:记忆与状态管理
人工智能·python·agent·adk·google agent
no_work9 小时前
万能图像处理小助手1.1_傅里叶变化_椒盐噪声_直方图均衡等图片批量处理
图像处理·人工智能·python