Search code examples
pythonlist-comprehension

Moving corner points of a rectangle in Python: is there a more elegant/compact solution?


I need to move the corner points of a rectangle by a given amount. I'm given an list of 4 3D points, each of which is a list of coordinates ([x,y,z]).

I have this, and it works OK, but feels awkward (pts is the given point list, and top, bot, and side are the given amounts to move the points):

# Get top and bottom points
upDownPts = sorted(pts, key=lambda k: [k[2]])
topPts = upDownPts[-2:]
botPts = upDownPts[0:2]

# adjust their Z coords
topPts[0][2] = topPts[0][2] - top
topPts[1][2] = topPts[1][2] - top
botPts[0][2] = botPts[0][2] + bot
botPts[1][2] = botPts[1][2] + bot

# Get left and right points
leftRightPts = sorted(pts, key=lambda k: [k[1]])
leftPts = leftRightPts[0:2]
rightPts = leftRightPts[-2:]

# adjust their Y coords
leftPts[0][1] = leftPts[0][1] + side
leftPts[1][1] = leftPts[1][1] + side
rightPts[0][1] = rightPts[0][1] - side
rightPts[1][1] = rightPts[1][1] - side

movedPts = pts

In particular, the additions and subtractions seem like they should be list comprehensions or somethng, but I couldn't make the syntax work so resorted to brute force.

Any suggestions welcome!


Solution

  • You could do something like this:

    # adjust their Z coords
    for point in topPts:
        point[2] -= top
    for point in botPts:
        point[2] += bot