I have a list of Point objects, each of which has an x and y property. I wish to calculate the maximum_x and maximum_y, without iterating through twice. I could do this:
max_x = max(points, key=lambda p: p.x)
max_y = max(points, key=lambda p: p.y)
But of course, this will iterate twice. I could do it manually, but since finding the maximum is so simple, I fear it'll increase clutter. Is there any way to do this with the built in max
function?
No, not really. What you already have is the best way, just calling max
twice.
Anyway, think about it like this: whether you iterate once and make two comparisons during each iteration, or you iterate twice and make one comparison during iteration, it does not make much difference in the end.
This would be possible using numpy assuming x
and y
are in one two-dimensional array:
import numpy as np
points_array = np.array([(p.x,p.y) for p in points])
xmax, ymax = points_array.max(axis=0)
But this would mean you would have to restructure your data. That being said, if that is the only reason you need numpy, I think I would stick with the clutter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With