Reputation: 1513
Let's say I have two lists (containing 2D positions):
pos1 = [100, 400]
pos2 = [200, 300]
Now I want to store the min x
and the min y
of these positions into min
and max
:
min_ = [min_x, min_y]
max_ = [max_x, max_y]
# in this case:
min_ = [100, 300]
max_ = [200, 400]
Actually, I am using a code like this:
min_ = []
max_ = []
min_.append(min(pos1[0], pos2[0]))
min_.append(min(pos1[1], pos2[1]))
max_.append(max(pos1[0], pos2[0]))
max_.append(max(pos1[1], pos2[1]))
Is there a more efficient way to do that?
Upvotes: 0
Views: 72
Reputation: 70307
If you're doing a lot with coordinates, you'll find numpy
makes a lot of these sorts of things more ergonomic.
import numpy as np
pos1 = np.array([100, 400])
pos2 = np.array([200, 300])
min_ = np.min([pos1, pos2], 0)
max_ = np.max([pos1, pos2], 0)
Upvotes: 1
Reputation: 46
Don't use keywords like min
and max
for variable names.
You could use list-comprehension and zip
:
minimum_values = [min(x,y) for x,y in zip(pos1, pos2)]
Upvotes: 1
Reputation: 70989
Maybe this:
min_ = [min(first, second) for first, second in zip(pos1, pos2)]
max_ = [max(first, second) for first, second in zip(pos1, pos2)]
By the way same but (maybe) a bit less readable:
min_ = [min(coords) for coords in zip(pos1, pos2)]
max_ = [max(coords) for coords in zip(pos1, pos2)]
NOTE: in terms of efficiency the two solutions are probably comparable this one simply avoids some code repetition.
Upvotes: 1