简体   繁体   English

根据另一个列表中元素的索引对列表进行排序

[英]Sort a list according to the index of the elements in another list

I have the following list:我有以下列表:

A = [0.9,0.8,...,0.1,0.0]

and another list:和另一个清单:

B = [8, 16, 53, 3, 6, 32, 1, 7, 0, 35] 

How can I make a sorted list similar to another list such that the biggest value in the second list will have the same index as the first list?如何制作一个类似于另一个列表的排序列表,以便第二个列表中的最大值与第一个列表具有相同的index

I want to sort list A like that:我想像这样对列表 A 进行排序:

A_sorted = [0.5, 0.6, 0.9, 0.2, 0.3, 0.7, 0.1, 0.4, 0.0, 0.8]
{B       = [8  , 16 , 53 , 3  , 6  , 32 , 1  , 7  , 0  , 35 ]} 

How is this possible in Python, preferably in a one line?这怎么可能在 Python 中,最好是一行?

Thanks all !谢谢大家!

You can do the following:您可以执行以下操作:

  1. create new versions of the two lists, sorted创建两个列表的新版本,排序
  2. map the sorted values of B to the sorted values of A using a dictionary map 使用字典将B的排序值转换为A的排序值
  3. build a new version of A_sorted by, for each value in B , looking up the corresponding value in B .B中的每个值构建一个新版本的A_sorted by,在B中查找相应的值。
values = [5, 8, 1, 3]
keys = [0.1, 0.4, 0.3, 0.2] 
sorted_values = sorted(values)
sorted_keys = sorted(keys)
merged = dict(zip(sorted_keys, sorted_values))
result = [merged[key] for key in keys]

This gives:这给出了:

>>> keys
[0.1, 0.4, 0.3, 0.2]
>>> result
[1, 8, 5, 3]

Fitting it on one line将其安装在一条线上

If you must, you could mash those statements together into two lines with something like:如果必须,您可以将这些语句组合成两行,例如:

merged = dict(zip(sorted(keys), sorted(values)))
result = [merged[key] for key in keys]

(or even in one, by inlining merged ). (甚至在一个中,通过内联合merged )。 But you lose readability.但是你失去了可读性。

How to puzzle this out on your own如何自己解决这个问题

The key to figuring this out by yourself is realising that you need to create a way to lookup, for any b , the corresponding value of a in the sorted lists.自己解决这个问题的关键是意识到您需要创建一种方法来查找任何b排序列表中a的相应值。 As soon as you realise this, you realise that you need a dictionary from sorted b to sorted a.一旦你意识到这一点,你就会意识到你需要一个从排序 b 到排序 a 的字典。

try below code:试试下面的代码:

a = [2,3,5,6,7]
b = [7,2,3,4,5]
sorted_b = sorted(b)
sorted_a = sorted(a)
for id,i in enumerate(sorted_b):
    idx = b.index(i)
    a[idx] = sorted_a[id]
print(a)

the answer I found was to sort the indexes of B one more time to get the inverse sorting indexes (where was each variable in the original vector) than use this as an index for the new vector like so:我找到的答案是将 B 的索引再排序一次以获得逆排序索引(原始向量中的每个变量在哪里),而不是将其用作新向量的索引,如下所示:

A[np.argsort(np.argsort(B))]

I used the suggestion of @batwannabe我使用了@batwannabe 的建议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM