python-2D列表的多个比较
作者:互联网
我有以下形式的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)
解决方法:
您可以使用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]
标签:nested-lists,list,python 来源: https://codeday.me/bug/20191119/2036892.html