根据另一个列表列表对列表列表进行排序

时间:2021-01-28 12:02:48

标签: python sorting python-2.x

我有一个列表列表,我想按照与另一个列表列表相同的顺序进行排序:

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

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

所以我想重新排列 l1 使其与 l2 的顺序相同。 (注意:这只是一个简单的测试用例。我正在处理的实际列表中有几个元素。

例如结果应该是:

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

使用python2(企业版)

2 个答案:

答案 0 :(得分:2)

使用python内置的sort

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

答案 1 :(得分:0)

它不是很漂亮或高效,但我认为这些不是要求:

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