简体   繁体   中英

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?

I want to sort list A like that:

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?

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
  3. build a new version of A_sorted by, for each value in B , looking up the corresponding value in 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 ). 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. As soon as you realise this, you realise that you need a dictionary from sorted b to sorted 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:

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

I used the suggestion of @batwannabe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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