Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list in Python using the result from sorting another list [duplicate]

Tags:

python

I have the two lists in Python

list_1 = [5, 2, 8];
list_2 = ['string1', 'string2', 'string3']

I would like to sort the fist list and use the result to sort the second list.

In other words, the result should be:

# Sorted in descending order
list_1_sorted = [8, 5, 2];
list_2_sorted = ['string3', 'string1', 'string2'];

I know how to sort each of these lists individually, but how I can permute one list using the permutation of indices resulting from sorting the other list?

like image 985
Amelio Vazquez-Reina Avatar asked Mar 03 '12 03:03

Amelio Vazquez-Reina


People also ask

How do I sort a list in Python to match another list?

Use the zip() and sorted() Functions to Sort the List Based on Another List in Python. In this method, we will use the zip() function to create a third object by combining the two given lists, the first which has to be sorted and the second on which the sorting depends.

Does sort function remove duplicates in Python?

Problems associated with sorting and removal of duplicates is quite common in development domain and general coding as well.


1 Answers

Schwartzian transform

list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2),
  key=operator.itemgetter(0), reverse=True))
like image 200
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 14:11

Ignacio Vazquez-Abrams