1

I am currently having 2 following classes:

class plane():
    def __init__(self):
        self.points = {}
        # Using dictionary is necessary, to be able refer a specific point by using its name (saved as dictionary key)
    def all_points(self):
        all_points = np.empty((3, len(self.points)))
        for k, point in enumerate(self.points.values()): # Line A
            all_points[k,:] = point.coordinate           # Line B
        return all_points

import numpy as np
class point():
    def __init__(self, x, y, z):
        self.coordinate = np.array((x, y, z))

My use case:

a = plane()
a.points[0] = point(0, 1, 2)
a.points[1] = point(1, 2, 3)
a.points[2] = point(2, 3, 4)
a.all_points()

Output:

array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])

Is it possible to replace the for loop with numpy operation? Since Numpy allows following operation:

x = np.array([[0, 1, 2], [2, 3, 4]])
x + 1

Output:

array([[1, 2, 3],
       [3, 4, 5]])

My idea was: a.points.values().coordniate. This obviously doesn't work as "dict value" object don't have "coordinate" methode.

Any suggestion is welcome. Thank you in advance for any feedback.

1
  • Since only a point object has a coordinate attribute, you can't avoid iterating in one way or other over all points. That's a Python level operation. The suggestions are just window dressing. Commented Feb 25, 2021 at 16:44

2 Answers 2

1

The builtin map can help:

np.array([*map(lambda x:x.coordinate,self.points.values())])

Internally map will be using its own loop. This only gets rid of the for loop in the code. It may have some performance improvements.

Execution:

class plane():
    def __init__(self):
        self.points = {}

    def all_points(self):
        return np.array([*map(lambda x:x.coordinate,self.points.values())])

class point():
    def __init__(self, x, y, z):
        self.coordinate = np.array((x, y, z))



a = plane()
a.points[0] = point(0, 1, 2)
a.points[1] = point(1, 2, 3)
a.points[2] = point(2, 3, 4)
print(a.all_points())

Output:

[[0 1 2]
 [1 2 3]
 [2 3 4]]
Sign up to request clarification or add additional context in comments.

Comments

0

I don't think you can do it without a for loop, but if you don't mind using a list comprehension then this should do it.

def all_points(self):
    all_points = np.stack(
        [self.points[k].coordinate for k in sorted(self.points)])
    return all_points

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.