![](/img/trans.png)
[英]Sort a list with duplicates based on another list with same items but different order
[英]Sort a different list based on another?
所以我有一些清单:
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]
因此,我想根据形状的高度(最大到最小)对形状进行排序。 对height_y列表进行排序确实很容易,但是高度基于与相同位置相关的形状。 因此,如果我对height_y进行排序,如何对list1进行排序,以使形状在排序后移到与height_y列表相同的位置? 但是,我不希望形状列表中的点的排列发生变化。
最终目标:
height_y = [150, 100]
list1 = [shape2, shape1]
注意:这里我仅使用两个形状(由点定义),但我希望它能够处理任意数量的形状(多达一百个)。
只需zip
并排序。
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]
分解:
zip(list1, height_y)
:将它们压缩在一起
sorted(---(1)---, key=lambda x: x[1], reverse=True)
:基于每个元组中的第一个值(高度)对元组进行反向排序
zip(*---(2)----)
:解压缩元组,您将获得两个元组的列表
map(list, ---(3)---)
:将元组列表转换为列表列表
如果您只有形状和高度。 我建议使用字典,然后按如下值对它进行排序:
import operator
dict = {}
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.