2016-05-14 53 views
0

我有打印出Rects列表这样如何从列表中找到最接近给定矩形的矩形?

[<rect(394, 28, 80, 100)>, <rect(394, 126, 80, 100)>, <rect(394, 224, 80, 100)>, <rect(472, 28, 80, 100)>, <rect(472, 126, 80, 100)>] 

的功能,我正在寻找一种方式,以符合上述任何给定的矩形从列表中最接近的矩形。

例如,像这样一个给定的Rect <rect(377, 231, 50, 70)>将与<rect(394, 224, 80, 100)>匹配并打印出来。

我已经试过这样做,与元组和元组的列表,通过使用min函数这样

temp_list = [(1, 3), (4, 9), (5, 7), (3, 5), (9, 4), (8, 4), (6, 1)] 
temp_tuple = (5, 11) 

nearest = min(temp_list, key=lambda c: (c[0] - temp_tuple[0]) ** 2 + (c[1] - temp_tuple[1]) ** 2) 

print(nearest) 

,但我不知道我怎么会做它矩形数据类型。

+2

,您已经对Python的做什么正确的观念,你的问题是,它没有很好地界定哪两个rects之间的距离是。它应该是中心之间的距离吗?角落之间的平均距离?双方的平均距离? –

回答

0

这样的事情,使用中心之间的距离为决胜局:

import math 

distance = 1000 

current_cx = current_rect.centerx 
current_cy = current_rect.centery 

for rect in rect_list: 
    cx = rect.centerx 
    cy = rect.centery 

    if math.sqrt(abs(current_cx-cx)**2 + abs(current_cy-cy)**2)) < distance: 
     nearest_rect = rect 
相关问题