如何从矩形列表中找到与给定矩形最近的矩形?

2024-04-25 17:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它可以打印出这样的矩形列表

[<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)

但我不知道如何使它适用于Rect数据类型。你知道吗


Tags: 方法lambdakey函数rect列表mintemp
1条回答
网友
1楼 · 发布于 2024-04-25 17:53:53

像这样,用两个中心之间的距离作为判定标准:

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

相关问题 更多 >