链接列表&在python中排序

时间:2017-10-15 22:25:27

标签: python

这是我想要的一个例子(Python 3.6):

List1= [1,2,3,4,5] #needed order
List2=[5,4,3,2,1] #inputted order.  
List3=[25,20,15,10,5] #order inputed linked with list2

以相同的顺序与List3相关联

List2List1的顺序或从最小到最大的顺序更改时的预期输出。 List3也会改变。

期望的输出:

List2=[1,2,3,4,5] #list change to correct order
List3=[5,10,15,20,25] #list stayed in correct position linked with list2

2 个答案:

答案 0 :(得分:1)

您正在寻找argsort功能。在python中,实现此目的的一种方法是使用sorted + enumerate

>>> [List3[x] for x, _ in sorted(enumerate(List2), key=lambda x: x[1])]
[5, 10, 15, 20, 25]

使用numpy,您可以执行以下操作:

>>> import numpy as np
>>> np.array(List3)[np.argsort(List2)]
array([ 5, 10, 15, 20, 25])

答案 1 :(得分:1)

这是在纯Python中实现它的另一种方法:

您压缩两个列表,然后按第一个(默认)元素排序。

In [18]: List2=[5,4,3,2,1]

In [19]: List3=[25,20,15,10,5]

In [20]: [b for _, b in sorted(zip(List2, List3))]
Out[20]: [5, 10, 15, 20, 25]

如果你想按第二个元素排序,你会这样做:

result = [b for _, b in sorted(zip(List2, List3), key=lambda x: x[1])]