Py学习  »  Python

python 3数组,反转多边形点

Programer Beginner • 4 年前 • 753 次点击  

我有一个坐标列表,但是x,y坐标不在一个元组中:

width,height = 100
#my_list = (x1, y1, x2, y2, ...)
#my_list = (0, 50, 50, 0, 50, 100)
my_list = (0, height/2, width/2, 0, width/2, height)

这些点可以创建多边形。在我的例子中,一个三角形填充了指向左侧的100x100区域的一半。

我正试图逆转( 水平 )三角形,所以它指向右边,所以解决方案是:

my_list = (width, height/2, width/2, 0, width/2, height)

但是我在想,我应该如何做一个函数,它可以水平地反转任何多边形?所以像这样:

my_list = (0, height/2, width/2, 0, width/2, height)
invert_horizontally(my_list, width, height)
>>> (100, 50, 50, 0, 50, 100)

我想,要想把这些点颠倒过来,我必须这样做:

for point in my_list:
    if this point is x:
        new_x = width - point
    else:
        pass

好吧,这是我的问题:如何确定这一点是x。还要如何用这段代码创建一个单行程序?

编辑:

迄今为止我的代码:

new_list = [ @@@-point for point in my_list ]

现在 @@@ 必须根据点是x还是y来改变。

编辑2:

基本上我需要那个 对于每个偶数项“点”,执行宽度点

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38238
 
753 次点击  
文章 [ 2 ]  |  最新文章 4 年前
blhsing
Reply   •   1 楼
blhsing    5 年前

您可以从 my_list , zip 与自身配对x和y坐标,并使用x和y的各自计算来获得反向坐标:

def invert_horizontally(my_list, width, height):
    i = iter(my_list)
    return [coord for x, y in zip(i, i) for coord in (width - x, y)]

所以给你的样本输入,

invert_horizontally(my_list, width, height)

返回:

[100, 50, 50, 0, 50, 100]
Neb
Reply   •   2 楼
Neb    5 年前

您知道点按顺序存储为 x, y 列表中的值。因此,你知道 x S处于偶数位置。一条直线可能是:

inverted_triangle = [width-coord if i % 2 == 0 else coord for i, coord in enumerate(triangle)]