按另外两个列表的顺序在python中对列表进行排序

时间:2019-05-07 06:26:07

标签: python list sorting

我有一个有趣的问题,目前我找不到任何解决方案。 具有两个具有相同值的列表,但顺序不同。我对一个列表重新排序,以使列表变得相同。很好,但是我还需要使用相同的键重新排序另一个第三列表。

我无法使用zip或枚举代码来检索第二个列表的新索引。

first=[(1,1,1),(2,2,2),(3,3,3)]
second=[(2,2,2),(3,3,3),(1,1,1)]
third=[2,3,1]

second=sorted(second,key=first.index)

print(second)

[(1,1,1),(2,2,2),(3,3,3)]

d = [i[0] for i in sorted(enumerate(second), key=lambda x:first.index)]

d应该为(2,0,1),但不起作用

第三个列表的目标是成为:[1,2,3]

2 个答案:

答案 0 :(得分:0)

要获取[1, 2, 3],请使用:

third = sorted(third, key=list(map(lambda x: x[0],first)).index)

要获取[2, 0, 1],请使用:

d = sorted(range(second), key=lambda x: first[x])

答案 1 :(得分:0)

此问题已解决。 如LINK所示,可以从重新排序的“第二个”中获取索引,然后使用此索引列表对其他任何列表进行排序。

Sort python list by order of another list AND retrieve old index

相关问题