代码之家  ›  专栏  ›  技术社区  ›  Programer Beginner

python 3数组,反转多边形点

  •  0
  • Programer Beginner  · 技术社区  · 7 年前

    我有一个坐标列表,但是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:

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   Neb    7 年前

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

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

    您可以从 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]
    
    推荐文章