Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

python - What is a Pythonic way to add a negative multiplication as a keyword argument

For some context, I am coding some geometric transformations into a python class, adding some matrix multiplication methods. There can be many 3D objects inside of a 3D "scene". In order to allow users to switch between applying transformations to the entire scene or to one object in the scene, I'm computing the geometric center of the object's bounding box (cuboid?) in order to allow that geometric center to function as the "origin" in the objects Euclidean space, and then to apply transformation matrix multiplications to that object alone.

My specific question occurs when mapping points from scene space to local object space, I subtract the geometric center from the points. Then after the transformation, to convert back, I add the geometric center to the points. Is there a pythonic way to change my function from adding to subtracting via keyword argument?

I don't like what I have now, it doesn't seem very pythonic.

def apply_centroid_transform(point, centroid, reverse=False):
    reverse_mult = 1
    if reverse:
        reverse_mult = -1

    new_point = [
        point[0] - (reverse_mult * centroid["x"]),
        point[1] - (reverse_mult * centroid["y"]),
        point[2] - (reverse_mult * centroid["z"]),
    ]

    return new_point

I don't want to have the keyword argument be multiply_factor=1 and then make the user know to type -1 there, because that seems unintuitive.

I hope my question makes sense. Thanks for any guidance you may have.

question from:https://stackoverflow.com/questions/65645999/what-is-a-pythonic-way-to-add-a-negative-multiplication-as-a-keyword-argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One line:

def apply_centroid_transform(point, centroid, reverse=False):
    return [point[i] - [1, -1][reverse]*centroid[j] for i, j in enumerate('xyz')]

It is not very readable, but it is very concise :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...