我有一个清单:
d = [23, 67, 110, 25, 69, 24, 102, 109]
如何将最近的值与动态间隙分组,并创建一个这样的元组,最快的方法是什么?:
[(23, 24, 25), (67, 69), (102, 109, 110)]
像
d = [23,67,110,25,69,24,102,109]
d.sort()
diff = [y - x for x, y in zip(*[iter(d)] * 2)]
avg = sum(diff) / len(diff)
m = [[d[0]]]
for x in d[1:]:
if x - m[-1][0] < avg:
m[-1].append(x)
else:
m.append([x])
print m
## [[23, 24, 25], [67, 69], [102, 109, 110]]
首先,我们计算顺序元素之间的平均差异,然后将差异小于平均值的元素组合在一起。