Reputation:
I have multiple lists with the following format:
list_one=['2','2','1','4','4','3','5','6']
list_two=['b','a','a','a','b','b','a','a']
list_three=['1','2','3','4','5','7','9','10']
How can I sort all these lists by list_one and list_two such that list_one takes precedence over list_two? The output would look like this after sorting:
list_one=['6','5','4','4','3','2','2','1']
list_two=['a','a','a','b','b','a','b','a']
list_three=['10','9','4','5','7','2','1','3']
Essentially we sort by the first list and then sort by the second list still respecting the sorting done by the first list, or sorting within the sorting that was done from list one. I have seen some methods done with zip but that is usually done by sorting only with one list. Any ideas?
Upvotes: 0
Views: 369
Reputation: 42143
You can do it with zip:
list_one=['2','2','1','4','4','3','5','6']
list_two=['b','a','a','a','b','b','a','a']
list_three=['1','2','3','4','5','7','9','10']
list_one,list_two,list_three = map(list,zip(*sorted(zip(list_one,list_two,list_three),reverse=True)))
print(list_one)
print(list_two)
print(list_three)
['6', '5', '4', '4', '3', '2', '2', '1']
['a', 'a', 'b', 'a', 'b', 'b', 'a', 'a']
['10', '9', '5', '4', '7', '1', '2', '3']
Applying zip to the 3 lists creates a list of tuples with the corresponding values of each list: [('6', 'a', '10'), ('5', 'a', '9'), ('4', 'b', '5'), ...
Sorting these tuples gives precedence to the first list over the second and third ones.
Applying zip(*...)
turns the list of (sorted) tuples back into 3 big tuples corresponding to each list. You can then reassign the 3 variables after mapping the tuples back into lists.
Another approach would be to build a list of indexes sorted using values from the first two lists and then map each list to the positions of the sorted indexes:
indexes = sorted(range(len(list_one)),key=lambda i:(list_one[i],list_two[i]))
list_one = [list_one[i] for i in indexes]
list_two = [list_two[i] for i in indexes]
list_three = [list_three[i] for i in indexes]
Upvotes: 2
Reputation: 77847
Zip the three lists in your sort order zip(list_one, list_two, list_three)
.
Sort the triples, and then unzip into your desired targets.
Upvotes: 0