【问题标题】:Defining 4 co-ordinates from 2 in a rectangular shape (python)从矩形中定义 2 个坐标(python)
【发布时间】:2022-01-08 01:10:00
【问题描述】:

所以我目前有 2 个点,格式为 [(x0, x1, y0, y1)],我知道这是一个矩形,但我希望更新这个列表,以便它是矩形的所有 4 个点。注意:矩形只能在网格上垂直或水平绘制,所以我知道 4 个角坐标是 (x1,y1),(x1, y2),(x2, y1),(x2,y2) 但是我不确定将其更改为所需格式的最佳方法是什么。我目前正在尝试在 python 上解决这个问题

【问题讨论】:

  • 到目前为止你写了什么?您能否展示可运行示例代码并说明示例所需的输出?
  • 你尝试了什么?你的代码在哪里?
  • 只需将原始值分配给 4 个变量并使用这些变量创建所有对。并停止搜索the best way - 搜索working way

标签: python arrays list format rectangles


【解决方案1】:

我不知道是什么问题。

只需将值分配给 4 个变量并使用它们创建 4 个对

简单示例:


rect = [(0, 1, 2, 3)]
print('rect  :', rect)

x1, x2, y1, y2 = rect[0]

points = [(x1, y1),(x1, y2),(x2, y1),(x2,y2)]
print('points:', points)

结果:

rect  : [(0, 1, 2, 3)]
points: [(0, 2), (0, 3), (1, 2), (1, 3)]

如果你有很多矩形,那么你可以使用for-loop

简单示例:

many_rects = [(0, 1, 2, 3), (10, 11, 12, 13)]
print('many_rects :', many_rects)

many_points = []

for rect in many_rects:
    x1, x2, y1, y2 = rect
    points = [(x1, y1),(x1, y2),(x2, y1),(x2,y2)]

    many_points.append(points)
    #many_points.extend(points)  # as flatten list
    
print('many_points:', many_points)

结果:

many_rects : [(0, 1, 2, 3), (10, 11, 12, 13)]
many_points: [[(0, 2), (0, 3), (1, 2), (1, 3)], [(10, 12), (10, 13), (11, 12), (11, 13)]]

# flatten list
many_points: [(0, 2), (0, 3), (1, 2), (1, 3), (10, 12), (10, 13), (11, 12), (11, 13)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多