Python测试点是否在矩形内

9

我刚开始学习Python,还在摸索中,但希望有经验的人可以帮助我。

我正试图编写一个Python脚本来:

  1. 创建四个点
  2. 创建四个矩形
  3. 检查每个点是否在任何一个矩形中,然后将结果写入输出文件。

问题涉及两种数据结构:Point和Rectangle类。我已经开始创建Point类和Rectangle类。 Rectangle类应该包含从随机模块的random方法创建的相关数据集。如您所见,我有点方向不清,但我已经使用 #注释来尝试说明我要做什么。

我具体的问题是:
1)如何使此脚本工作?
2)我缺少哪些变量或函数来生成随机矩形,并查看特定点是否在这些矩形中?

## 1. Declare the Point class
class Point:
    def __init__(self,x = 0.0, y = 0.0): 
        self.x = x 
        self.y = y
    pass
## 2. Declare the Rectangle class 
class Rectangle: 
    def __int__(self): ## A rectangle can be determined aby (minX, maxX) (minY, maxY) 
        self.minX = self.minY = 0.0 
        self.maxX = self.maxY = 1.0 
    def contains(self, point): ## add code to check if a point is within a rectangle 
        """Return true if a point is inside the rectangle."""
        # Determine if a point is inside a given polygon or not
        # Polygon is a list of (x,y) pairs. This function
        # returns True or False. 
    def point_in_poly(x,y,poly):
        n = len(poly)
        inside = False
        p1x,p1y = poly[0]
        for i in range(n+1):
            p2x,p2y = poly[i % n]
            if y > min(p1y,p2y):
                if y <= max(p1y,p2y):
                    if x <= max(p1x,p2x):
                        if p1y != p2y:
                            xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
            p1x,p1y = p2x,p2y
        return inside
## 3. Generate four points 
##define a Point list to keep four points 
points = []
##add codes to generate four points and append to the points list
polygon = [(0,10),(10,10),(10,0),(0,0)]
point_x = 5
point_y = 5

## 4. Generate four rectangles 
##define a Rectangle list 
rects = [] 
for i in range(4):
    rectangle = Rectangle() 
    ## Generate x 
    x1 = random.random() 
    x2 = random.random() 
    ## make sure minX != maxX 
    while(x1 == x2): 
        x1 = random.random() 
    if x1<x2: 
        rectangle.minX=x1 
        rectangle.maxX=x2 
    elif x1>x2:
        rectangle.minX=x2
        rectangle.maxX=x1
    rects.append(rectangle)
    ## Develop codes to generate y values below 
    ## make sure minY != maxY 
    while(y1 == y2):
        y1 = random.random()
    if y1<y2:
        rectangle.minY=y1
        rectangle.maxY=y2
    elif y1>y2:
        recetangle.minY=y2
        racetangle.maxY=y1
    ## add to the list 
    rects.append(rectangle)

## 5. Add code to check which point is in which rectangle 
resultList = [] ## And use a list to keep the results 
for i in range(4):
    for j in range(4):
        if points[i] in rectangle[j]:
            print i

# write the results to file
f=open('Code5_4_1_Results.txt','w') 
for result in resultList:
    f.write(result+'\n') 
f.close()

你的问题太宽泛了。按照现在的说法,听起来像是在说:“请教我吧!”,这对于问答格式并不好。请编辑以包含具体问题。可选地,将它们放在项目符号列表中,使它们单独突出。 - Palu Macil
Palu - 对于 Python 和 Stackoverflow 我还是新手,我正在学习如何请求帮助的协议。我将一些我学习过的脚本组合在一起,尝试着找出如何创建随机矩形,然后查看这些点是否适合任何一个矩形。现在我遇到了以下错误: Traceback (most recent call last): File "C:\Code5_4_1_Creating4PolyRectandCheckRelationships.py", line 62, in <module> while(y1 == y2): NameError: name 'y1' is not defined - Geonerd
没问题。通过改进您的帖子,可以更容易地帮助您、其他人,并增加您被看到的机会。我也不是管理员(甚至不接近),除非有人试图做坏事,否则我也不会投反对票,所以您不必担心我的建议。 :) 它只是为了提供提示而存在。 - Palu Macil
2个回答

13

这是相当简单的数学。假设有一个矩形,其点为(x1,y1)和(x2,y2),并且假设 x1 < x2y1 < y2(如果没有,您可以交换它们),那么一个点(x,y)在该矩形内部如果满足条件x1 < x < x2 and y1 < y < y2。由于Python比较运算符可以进行链式比较,因此这甚至是有效的Python代码,应该会产生正确的结果(在其他语言中,你必须编写如x1 < x and x < x2等的代码)。

如果您愿意,可以使用<= 代替<。使用<=表示矩形边界上的点(例如点(x1,y1))计入其内部,而使用<则意味着这样的点在外部。


好的,我解决了。现在我得到了以下错误: Traceback (most recent call last): File "C:\Code5_4_1_Creating4PolyRectandCheckRelationships.py", line 80, in <module> if points[i] in rectangle[j]: IndexError: 列表索引超出范围 - Geonerd
1
我不是来为你编写代码的,但如果你想用它来测试点是否在矩形内,那么请将你的Rectangle类中的contains更改为__contains__。(另外,你应该在__init__处使用__int__。)如果你仍然有问题,请尝试一些方法,如果你仍然无法解决它,我建议你提出一个新的问题,而不是在这里评论。 - celticminstrel
谢谢你,Celticminstrel。你的建议很有帮助。我不是想表现出只想要答案的样子。相反,我是想得到帮助,找出答案,这样我就能从这次经历中学到东西。 - Geonerd
2
需要注意的是,此答案假定矩形与坐标轴平行。 - Puco4
1
如果矩形不平行于X和Y轴,它将无法工作。 - PhiloRobotist
显示剩余3条评论

6

最好编写单独的函数来完成该任务。下面是我的函数,如果需要可以直接复制。

def pointInRect(point,rect):
    x1, y1, w, h = rect
    x2, y2 = x1+w, y1+h
    x, y = point
    if (x1 < x and x < x2):
        if (y1 < y and y < y2):
            return True
    return False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接