[ A more elegant way to sort 3 lists in Python ]
I have 3 lists that I want to sort the lists "relative" to each other (for example, picturing each list as a row in a 3x3 matrix, I want to sort it by columns) .
I am wondering if there is a more elegant way to do this. What I come up with is using a temporary list, below is a simplified example:
list1 = ['c','b','a']
list2 = [6,5,4]
list3 = ['some-val-associated-with-c','another_value-b','z_another_third_value-a']
tmp, list2 = (list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0])))
list1, list3 = (list(x) for x in zip(*sorted(zip(list1, list3), key=lambda pair: pair[0])))
print(list1, '\n', list2, '\n', list3)
[1, 2, 3] [4, 5, 6] ['a', 'b', 'c']
Output (the actual AND desired output):
['a', 'b', 'c']
[4, 5, 6]
['z_another_third_value-a', 'another_value-b', 'some-val-associated-with-c']
And what I not want is:
['a', 'b', 'c']
[4, 5, 6]
['another_value-b', 'some-val-associated-with-c', 'z_another_third_value-a']
Answer 1
list1, list2, list3 = zip(*sorted(zip(list1, list2, list3)))