How to sort multiple by another list efficiently in Python

Question:

sorter_lst = [4,-1,5,6,7,-2]
lst_a = [1,2,3,4,5,6]
lst_b = [7,8,9,10,11,12]
lst_c = [13,14,15,16,17,18]

desired output is all lists sorted by the sorter_lst

lst_a = [6,2,1,3,4,5]
lst_b = [12,8,7,9,10,11]
lst_c = [18,14,13,15,16,17]

I would like to do this in one line with one sort. I know it can be done in 3 lines like this

lst_a = [a for (y,a) in sorted(zip(sorter_lst,lst_a),key=lambda pair: pair[0])]
lst_b = [b for (y,b) in sorted(zip(sorter_lst,lst_b),key=lambda pair: pair[0])]
lst_c = [c for (y,c) in sorted(zip(sorter_lst,lst_c),key=lambda pair: pair[0])]

But I am looking for a more efficient way to do this.

What I have tried…

test_output = [[a,b,c] for (y,a,b,c) in sorted(zip(sorter_lst,lst_a,lst_b,lst_c),key=lambda pair: pair[0])]

which gives me

test_output = [[5,11,17],[2,8,14],[6,12,18],[1,7,13],[3,9,15],[4,10,16]]

The first entry of test_output contains index 0 of the desired output of lst_a, lst_b, and lst_c.

Asked By: Michael Schmitz

||

Answers:

You can use zip twice:

sorter_lst = [4,-1,5,6,7,-2]
lst_a = [1,2,3,4,5,6]
lst_b = [7,8,9,10,11,12]
lst_c = [13,14,15,16,17,18]

_, lst_a, lst_b, lst_c = zip(*sorted(zip(sorter_lst, lst_a, lst_b, lst_c)))

print(lst_a) # (6, 2, 1, 3, 4, 5)
print(lst_b) # (12, 8, 7, 9, 10, 11)
print(lst_c) # (18, 14, 13, 15, 16, 17)
Answered By: j1-lee
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.