我有一个列表列表,我想按照与另一个列表列表相同的顺序进行排序:
l1 = [['hello', 'test'], ['there', 'correct'], ['Elem3', 'yes']]
l2 = [['hello'], ['Elem3'], ['there']]
所以我想重新排列 l1 使其与 l2 的顺序相同。 (注意:这只是一个简单的测试用例。我正在处理的实际列表中有几个元素。
例如结果应该是:
l1 = [['hello', 'test'], ['Elem3', 'yes'], ['there', 'correct']]
使用python2(企业版)
答案 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']]