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?
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.
Problems associated with sorting and removal of duplicates is quite common in development domain and general coding as well.
Schwartzian transform
list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2),
key=operator.itemgetter(0), reverse=True))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With