【问题标题】:Python Test If Point is in RectanglePython测试点是否在矩形中
【发布时间】:2020-04-19 03:17:52
【问题描述】:

我是 python 新手,仍在学习中,但我希望有更多经验的人可以帮助我。

我正在尝试编写一个 python 脚本:

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

问题涉及两个数据结构Point和Rectangle类。我已经开始创建 Point 类和 Rectangle 类。 Rectangle 类应该包含从 random 模块的 random 方法创建的相关数据集。从我的尝试中你可以看出,我有点到处都是,但我使用#cmets 来尝试得到我想要做的事情。

我的具体问题是:
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 - 作为 Python 和 Stackoverflow 的新手,我猜我仍在学习寻求帮助的协议。我将一些我一直在学习的脚本组合到这个脚本中,试图弄清楚如何创建随机矩形,然后查看这些点是否适合这些矩形中的任何一个。现在我收到以下错误: Traceback(最近一次调用最后一次):文件“C:\Code5_4_1_Creating4PolyRectandCheckRelationships.py”,第 62 行,在 while(y1 == y2): NameError: name 'y1' is not定义
  • 没关系。通过改进您的帖子,可以更轻松地帮助您和其他来访者,并让您有更好的机会被看到。我也不是版主(甚至没有关闭),除非有人试图做坏事,否则我也不会投反对票,所以你不必担心我的建议。 :) 它只是在这里提供提示。

标签: python geospatial


【解决方案1】:

这是非常简单的数学运算。给定一个包含点 (x1,y1) 和 (x2,y2) 的矩形,并假设 x1 &lt; x2y1 &lt; y2(如果没有,您可以交换它们),如果 @987654323 则点 (x,y) 在该矩形内@。由于可以链接 Python 比较运算符,这甚至是应该产生正确结果的有效 Python 代码(在其他语言中,您必须编写诸如 x1 &lt; x and x &lt; x2 之类的东西)。

如果需要,您可以使用&lt;= 代替&lt;。使用&lt;= 表示矩形边界上的点(例如,点 (x1,y1))算作在矩形内部,而使用&lt; 则表示这些点在矩形外部。

【讨论】:

  • 感谢 Celticminstrel 解释了这个脚本的矩形类部分。从那以后。现在我试图让它与脚本的其余部分一起流动,但我收到了这个错误: Traceback(最近一次调用最后一次):文件“C:\Code5_4_1_Creating4PolyRectandCheckRelationships.py”,第 62 行,在 while(y1 = = y2): NameError: name 'y1' is not defined
  • 好吧,我想通了。现在我得到: Traceback(最近一次调用最后一次):文件“C:\Code5_4_1_Creating4PolyRectandCheckRelationships.py”,第 80 行,在 如果 points[i] in rectangle[j]: IndexError: list index out of range跨度>
  • 我不是来为你编写代码的,但如果你想用它来测试点是否在矩形中,那么在你的 Rectangle 类中更改 contains__contains__。 (另外,你有__int__,你应该有__init__。)如果你仍然有问题,尝试一下,如果你仍然无法解决它,我建议提出一个新问题而不是在这里发表评论。
  • 谢谢 Celticminstrel。您的建议有所帮助。我并不是想知道我想要的只是答案。相反,我试图寻求帮助以找出答案,以便我可以从这次经历中学习。
  • x1 &lt; x &lt; x2 and y1 &lt; y &lt; y2 不起作用 x1 将大于 x2。例如:9 &lt; 8 &lt; 7
【解决方案2】:

最好编写一个单独的函数来完成这项工作。这是我的功能。如果你愿意,你可以复制它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多