1 回答
TA贡献1859条经验 获得超6个赞
您可以使用enumerateanditertools.combinations来缩短:
from itertools import combinations
out = defaultdict(lambda: defaultdict(dict))
for (i, v1), (j, v2) in combinations(enumerate(yhat), 2):
out.setdefault(i, {})[j] = euclidean(v1, v2)
out
{0: {1: 17.320508075688775, 2: 22.360679774997898, 3: 183.3712082089225, 4: 190.3286631067428},
1: {2: 14.142135623730951, 3: 166.80827317612278, 4: 173.8533865071371},
2: {3: 170.07351351694948, 4: 176.4227876437735},
3: {4: 14.142135623730951}}
其中 out 映射到输入列表中的索引到这些索引处的向量之间的距离。您可以获得距离小于阈值的向量的最大元素,例如:
for (i, v1), (j, v2) in combinations(enumerate(yhat), 2):
if euclidean(v1, v2) < threshold:
out.setdefault(i, {})[j] = (max(v1), max(v2))
out
{0: {1: (220, 230), 2: (220, 230), 3: (220, 300), 4: (220, 300)},
1: {2: (230, 230), 3: (230, 300), 4: (230, 300)},
2: {3: (230, 300), 4: (230, 300)},
3: {4: (300, 300)}}
添加回答
举报