每当您需要处理组合问题(例如“我需要首先和第二个,然后是第一和第三个,然后...”)时,itertools
模块通常都会有您需要的工具。
from math import hypot
def distance(p1,p2):
"""Euclidean distance between two points."""
x1,y1 = p1
x2,y2 = p2
return hypot(x2 - x1, y2 - y1)
from itertools import combinations
list_of_coords = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]
[distance(*combo) for combo in combinations(list_of_coords,2)]
Out[29]:
[2.8284271247461903,
5.656854249492381,
8.48528137423857,
11.313708498984761,
14.142135623730951,
2.8284271247461903,
5.656854249492381,
8.48528137423857,
11.313708498984761,
2.8284271247461903,
5.656854249492381,
8.48528137423857,
2.8284271247461903,
5.656854249492381,
2.8284271247461903]
编辑:你的问题有点令人困惑。以防万一,如果您只想将第一个观点与其他观点进行比较:
from itertools import repeat
pts = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]
[distance(*pair) for pair in zip(repeat(pts[0]),pts[1:])]
Out[32]:
[2.8284271247461903,
5.656854249492381,
8.48528137423857,
11.313708498984761,
14.142135623730951]
但是通常在这种问题中,您关心所有组合,因此我将保留第一个答案。