![](/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.