【发布时间】:2011-06-08 01:06:15
【问题描述】:
我有两个列表(长度可能相同也可能不同)。在每个列表中,是一系列由两个点组成的元组(基本上是 X、Y 值)。
我将这两个列表相互比较,以找到具有相似点值的两个点。我尝试过列表理解技术,但它与列表中的嵌套元组真的很混淆,我无法让它工作。
这是最好(最快)的方法吗?我觉得可能有一种更 Pythonic 的方式来做到这一点。
假设我有两个列表:
pointPairA = [(2,1), (4,8)]
pointPairB = [(3,2), (10,2), (4,2)]
然后是一个用于存储对的空列表和一个仅存储匹配对的容差值
matchedPairs = []
tolerance = 2
然后这个循环解包元组,比较差异,并将它们添加到matchedPairs列表中以指示匹配。
for pointPairA in pointPairListA:
for pointPairB in pointPairListB:
## Assign the current X,Y values for each pair
pointPairA_x, pointPairA_y = pointPairA
pointPairB_x, pointPairB_x = pointPairB
## Get the difference of each set of points
xDiff = abs(pointPairA_x - pointPairB_x)
yDiff = abs(pointPairA1_y - pointPairB_y)
if xDiff < tolerance and yDiff < tolerance:
matchedPairs.append((pointPairA, pointPairB))
这将导致matchedPairs看起来像这样,里面有两个点元组的元组:
[( (2,1), (3,2) ), ( (2,1), (4,2) )]
【问题讨论】:
-
如果您可以使用“距离”而不是平方作为公差,您可以使用复数而不是元组,例如。
[2+1j, 4+8j]。然后您可以将abs(pt1-pt2)与容差进行比较