按值接近度对列表进行分组

时间:2015-11-21 21:39:03

标签: list python-2.7 group-by

我怎样才能对表格列表进行分组

((1156.0,167,78309.39),(1158.0,168,78322.731),(1156.0,169,65375.50),(34.0,221,64669.58),(34.0,222,91244.20),(35.0,223,90929.57) ),(34.0,224,90857.39))

基于Python中每个嵌套列表中的第一个值的单独列表。我希望列表以彼此的几个数字内的值开头组合在一起,因此结果如下所示: ((1156.0,167,78309.39),(1158.0,168,78322.73),(1156.0,169,65375.50))

((34.0,221,64669.58),(34.0,222,91244.20),(35.0,223,90929.57),(34.0,224,90857.39))

谢谢!

1 个答案:

答案 0 :(得分:0)

这应该有效

x = ((1156.0, 167, 78309.39), (1158.0, 168, 78322.731), (1156.0, 169, 65375.50), (34.0, 221, 64669.58), (34.0, 222, 91244.20), (35.0, 223, 90929.57), (34.0, 224, 90857.39))
max_step = 10
result = []
prev = None
for y in sorted(x):
    if prev and y[0] - prev < max_step:
        result[-1].append(y)
    else:
        result.append([y])
        prev = y[0]