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)