简体   繁体   中英

Sort a different list based on another?

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

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:

  1. zip(list1, height_y) : zip them together

  2. sorted(---(1)---, key=lambda x: x[1], reverse=True) : sort the tuples in reverse based on the first value in each tuple (the height)

  3. zip(*---(2)----) : unzip the tuples, you get a list of two tuples

  4. map(list, ---(3)---) : convert list of tuple to list of lists

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM