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)

相关推荐
databook12 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室12 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三14 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271117 小时前
Python之语言特点
python
刘立军17 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机21 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python