0

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?

2
  • 1
    min_x, max_x = sorted(pos1[0], pos2[0]), same for y Commented Apr 6, 2021 at 15:01
  • Yeah, but it works only if I have two positions (but in this case this functions). Commented Apr 6, 2021 at 15:10

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The second approach is not less readable (IMO) and also generalizes for more coordenates
It's only that in those cases the more "sexy", short list-comprehension falls short over a good old-fashioned loop that only iterates the zip once and constructs both resulting lists...
1

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)]

2 Comments

If we're talking about good variable naming conventions, I'd recommend not using x and y for the comprehension variables when they both refer to vectors which each have a respective X and Y coordinate.
OP uses min_ and max_. that doesn't override the built-ins...
1

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)

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.