Reputation: 5
So I have some lists:
shape1 = [[0, 0], [0, 100], [100, 100], [100, 0]]
shape2 = [[300, 300], [300, 450], [450, 450], [450, 300]]
list1 = [shape1, shape2]
height_y = [100, 150]
So I want to sort the shapes based on their heights (largest to smallest). It's really easy to sort the height_y list, however the heights are based on the shapes which are correlated to the same positions. So if I sort height_y, how can I sort list1 so that the shapes move into the same position as the height_y list after being sorted? I do not however want the arrangement of the points in the shape lists to change.
End Goal:
height_y = [150, 100]
list1 = [shape2, shape1]
Note: I'm only using two shapes here (defined by points) but I want this to be able to work with any number of shapes (upwards of a hundred).
Upvotes: 0
Views: 82
Reputation: 153
If you have only shape and height. I suggest to use dictionary and then sort it by value like:
import operator
dict = {}
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))
Upvotes: 1
Reputation: 402353
Just zip
em and sort.
In [489]: list1, height_y = map(list, (zip(*sorted(zip(list1, height_y), key=lambda x: x[1], reverse=True))))
In [490]: list1
Out[490]: [shape2, shape1] # shortened for aesthetic purposes (it's a list of lists)
In [491]: height_y
Out[491]: [150, 100]
Breakdown:
zip(list1, height_y)
: zip them together
sorted(---(1)---, key=lambda x: x[1], reverse=True)
: sort the tuples in reverse based on the first value in each tuple (the height)
zip(*---(2)----)
: unzip the tuples, you get a list of two tuples
map(list, ---(3)---)
: convert list of tuple to list of lists
Upvotes: 5