簡體   English   中英

根據另一個列表列表對列表列表進行排序

[英]Sorting list of lists based on another list of lists

我有一個列表列表,我想按照與另一個列表列表相同的順序進行排序:

l1 = [['hello', 'test'], ['there', 'correct'], ['Elem3', 'yes']]

l2 = [['hello'], ['Elem3'], ['there']]

所以我想重新排列l1,使其與l2的順序相同。 (注意:這只是一個簡單的測試用例。我正在處理的實際列表中有幾個元素。

例如結果應該是:

l1 = [['hello', 'test'], ['Elem3', 'yes'], ['there', 'correct']]

使用python2(企業)

使用 python 的內置sort

l1.sort(key=lambda pair: l2.index(pair[0]))

它不是非常漂亮或高效,但我認為這些不是要求:

>>> l3 = [None] * len(l2)
>>> for item in l1:
...     l3[l2.index([item[0]])] = item
>>> print l3
[['hello', 'test'], ['Elem3', 'yes'], ['there', 'correct']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM