2D列表的多重比较

时间:2015-10-26 06:15:30

标签: python list nested-lists

我有以下形式的2D列表:

xyPositions = [[474, 318], [543, 432], [633, 328], [548, 514]]

有时这些列表中有4对(如此处),8,10,12或16对xy坐标。

我编写的以下小函数将测试两组x y坐标是否重叠,例如,dotOverlap( [55, 99], [399, 88] )

然而,我有点尴尬地说我想不出一种简单的方法来测试所有可能的重叠情况(即成对比较):

#    #
1 to 2
1 to 3
1 to 4
2 to 3
2 to 4
3 to 4

我如何以编程方式执行此操作?

from math import sqrt
ClearanceRadius = 7     # pixels
def dotOverlap(p1, p2):

    x1 = p1[0]
    y1 = p1[1]
    x2 = p2[0]
    y2 = p2[1]

    overLapTest = None

    d = sqrt( (y2 - y1)**2 + (x2 - x1)**2 )

    if ClearanceRadius*2 < d:
        overLapTest = False
    elif ClearanceRadius*2 > d:
        overLapTest = True

    return(overLapTest)

1 个答案:

答案 0 :(得分:3)

您可以使用itertools.combinations生成所有组合,然后您可以逐个解压缩您的功能组合,就像这样

>>> from itertools import combinations
>>> xyPositions = [[474, 318], [543, 432], [633, 328], [548, 514]]
>>> [dotOverlap(*items) for items in combinations(xyPositions, r=2)]
[False, False, False, False, False, False]