1

I'm absolutely sure this question must have been asked multiple times before, but for the life of me i couldn't find a thread answering this question:

I am making a model exporter where i want to calculate the minimum and maximum bounds of each object, by going through a list of vertices and picking the lowest and highest x, y, and z values into their own min/max tuple on the same form. The way i do this right now is like this:

x = max(vertices,key=itemgetter(0))[0] y = max(vertices,key=itemgetter(1))[1] z = max(vertices,key=itemgetter(2))[2] extents_max = (x, y, z) x = min(vertices,key=itemgetter(0))[0] y = min(vertices,key=itemgetter(1))[1] z = min(vertices,key=itemgetter(2))[2] extents_min = (x, y, z) 

And this works, but is there a more elegant, one-liner way of doing this in python?

4
  • 3
    Can you give a simple, reproducible example of what vertices might look like? Commented Feb 4, 2018 at 16:01
  • Also why are you taking the first and second elements of lists for y and z respectively? Commented Feb 4, 2018 at 16:02
  • maps seems to be the thing you strive for but, just give us vertices and a bit more of the code Commented Feb 4, 2018 at 16:03
  • "vertices" is a list of tuples on the form (x, y, z). I use max() / min() to sort the tuples by item 0 (x), 1 (y), and 2 (z), then i retrieve the item i sorted by for each axis and use them to build a new tuple. Commented Feb 5, 2018 at 11:21

3 Answers 3

2

Just remove your repeated 0, 1, 2, it's a one-liner:

extents_max = [max(vertices,key=itemgetter(i))[i] for i in range(3)] 

If you need it to remain a tuple as you have shown in your example:

extents_max = tuple(max(vertices,key=itemgetter(i))[i] for i in range(3)) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Not as compact as Willem's answer, but more readable in my opinion, hence marked as answer!
1

You can calculate these with sequence unpacking:

mins, maxs = zip(*[(min(map(itemgetter(i), vertices)), max(map(itemgetter(i), vertices))) for i in range(3)]) 

For example:

>>> vertices = [(1,4,2), (1,3,0), (4,2,5)] >>> mins, maxs = zip(*[(min(map(itemgetter(i), vertices)), ... max(map(itemgetter(i), vertices))) ... for i in range(3)]) >>> mins (1, 2, 0) >>> maxs (4, 4, 5) 

Comments

0

Demodata:

verts = [(-94, -24, -87), (90, 27, -56), (-22, -59, -44), (50, -70, 52), (-31, 37, -24), (-73, 53, 66), (-47, -28, 99), (-3, -42, -66), (2, 85, 58), (79, -86, 39)] 

Find min/max:

z = [(min(l),max(l)) for l in zip(*verts)] # [(min,max) for each # (x0,..,xn),(y0,..,yn),(z0,..,zn) ] extends_min, extends_max = zip(*z) print(extends_min, extends_max) 

Output:

(-94, -86, -87) (90, 85, 99) 

1 Comment

unfortunately thats about the same as @WillemVanOnsem does - and he gots it in a one liner :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.