Sorting A List In Python Using The Result From Sorting Another List
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 oth
Solution 1:
list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2),
key=operator.itemgetter(0), reverse=True))
Solution 2:
Zip the lists together, sort, unzip the lists:
together = zip(list_1, list_2)
sorted_together = sorted(together)
list_1_sorted = [x[0] for x in sorted_together]
list_2_sorted = [x[1] for x in sorted_together]
What's happening here is that zip creates a list of tuples, with the elements you want the list to be sorted by being the first elements:
>>> a = [1,3,7,3,2]
>>> b = ["one","two",'three','four','five']
>>> zip(a,b)
[(1, 'one'), (3, 'two'), (7, 'three'), (3, 'four'), (2, 'five')]
Then when you sort them, they elements stay paired:
>>> sorted(zip(a,b))
[(1, 'one'), (2, 'five'), (3, 'four'), (3, 'two'), (7, 'three')]
Then all that's left is to unpack these lists.
Solution 3:
You can use zip
:
>>>list_1 = ['string1', 'string2', 'string3']>>>list_2 = [5, 2, 8]>>>s = sorted(zip(list_2, list_1), reverse=True)>>>list_1_sorted = [e[1] for e in s]>>>list_2_sorted = [e[0] for e in s]>>>list_1_sorted
['string3', 'string1', 'string2']
>>>list_2_sorted
[8, 5, 2]
>>>
Solution 4:
@Ignacio's answer is the best, but just in case you need to sort the lists in-place without making new lists, you can try this:
import itertools
list_enumerate = itertools.count()
list_2.sort(reverse=True, key=lambda k: list_1[next(list_enumerate)])
list_1.sort(reverse=True)
print list_1
print list_2
Note that I do not think there is any guarantee that the key
function is called for each list item in order (which is necessary for this to work), so this is a risky method to use.
Post a Comment for "Sorting A List In Python Using The Result From Sorting Another List"