Home > Blockchain >  Sort a list given another index list in Python
Sort a list given another index list in Python

Time:05-06

I want to create a new list with the elements of a list, but sorted according to the values of another list.

Example:

list = [12, 17, 26, 28, 29, 33, 34, 37, 41, 43, 45, 64, 70]

index_list = [9, 10, 0, 1, 2, 6, 8, 7, 3, 5, 4, 11, 12]

the result should be:

final_list = [26, 28, 29, 41, 45, 43, 33, 37, 34, 12, 17, 64, 70]

I tried to do it with the insert method:

final_list = []
for i in range(len(list)):
   final_list.insert(index_list[i], list[i])
print(final_list)

but the output is not correct:

[26, 28, 29, 41, 45, 12, 43, 17, 33, 34, 37, 64, 70]

CodePudding user response:

There's really no need to sort anything:

alist = [12, 17, 26, 28, 29, 33, 34, 37, 41, 43, 45, 64, 70]
index_list = [9, 10, 0, 1, 2, 6, 8, 7, 3, 5, 4, 11, 12]

res = [0] * len(index_list)
for i, j in enumerate(index_list):
    res[j] = alist[i]

print(res)

prints

[26, 28, 29, 41, 45, 43, 33, 37, 34, 12, 17, 64, 70]
 

CodePudding user response:

zip the two lists together (with the indices as the first part of each tuple) and sort the result:

>>> a_list = [12, 17, 26, 28, 29, 33, 34, 37, 41, 43, 45, 64, 70]
>>> index_list = [9, 10, 0, 1, 2, 6, 8, 7, 3, 5, 4, 11, 12]
>>> sorted(zip(index_list, a_list))
[(0, 26), (1, 28), (2, 29), (3, 41), (4, 45), (5, 43), (6, 33), (7, 37), (8, 34), (9, 12), (10, 17), (11, 64), (12, 70)]

Then just pull out the elements corresponding to the original a_list:

>>> [i[1] for i in sorted(zip(index_list, a_list))]
[26, 28, 29, 41, 45, 43, 33, 37, 34, 12, 17, 64, 70]

CodePudding user response:

Similar to Antony's, but more direct (no need for extra indexes by enumerate):

alist = [12, 17, 26, 28, 29, 33, 34, 37, 41, 43, 45, 64, 70]
index_list = [9, 10, 0, 1, 2, 6, 8, 7, 3, 5, 4, 11, 12]

res = [None] * len(alist)
for i, res[i] in zip(index_list, alist):
    pass

print(res)

Output (Try it online!):

[26, 28, 29, 41, 45, 43, 33, 37, 34, 12, 17, 64, 70]
  • Related