检查列表中的所有点都在矩形内

  • 本文关键字:列表 python-3.x
  • 更新时间 :
  • 英文 :


我已经编写了以下代码,但由于某种原因,它仅适用于列表中的第一点:

def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
x1, y1 = firstCorner[0], firstCorner[1]
x2, y2 = secondCorner[0], secondCorner[1]
for i in range(len(pointList)):
xa = pointList[i][0]
ya = pointList[i][1]
if (xa in range(x1,x2+1)) and (ya in range(y1,y2+1)):
return True
elif (xa in range(x2,x1+1)) and (ya in range(y2,y1+1)):
return True
else:
return False

此代码仅适用于检查列表中的第一个坐标:

allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]) 

返回 True

然而

allIn((0,0), (5,5), [(1,1), (8,0), (5,6)]) 

也返回 True

有什么建议吗?

您可以将函数更改为:

def all_in(first_corner=(0,0), second_corner=(0,0), point_list=None):
point_list = point_list or []
x1, y1 = first_corner[0], first_corner[1]
x2, y2 = second_corner[0], second_corner[1]
return all(p[0] in range(x1,x2+1) and p[1] in range(y1,y2+1) for p in point_list)

这样可以避免检查任何点,并在点不在矩形内时立即返回False

最新更新