Reputation: 32558
What is the proper way to order elements in one list based on values of two (or more lists) in base Python. Say I have three lists:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [0, 1, 1, 0, 1, 2, 2, 0, 1]
Z = [2, 1, 2, 1, 2, 1, 2, 1, 1]
I want to order the values of X
first based on Z
and then based on Y
. The desired output would be:
["d", "h", "b", "i", "f", "a", "c", "e", "g"]
Upvotes: 0
Views: 53
Reputation: 152860
You could simply zip
the lists and then use sorted
plus unpacking:
>>> [i[2] for i in sorted(zip(Z, Y, X))]
['d', 'h', 'b', 'i', 'f', 'a', 'c', 'e', 'g']
By zip
ping it with Z
first and Y
as second input it will give the desired order - and the outer comprehension discards the Z
and Y
again leaving you with the X
values. Okay, in case both Z
and Y
are equal it will breaks ties by comparing the X
(which could be undesired according to the question), you could disable that by using a custom key
function that excludes X
:
>>> [i[2] for i in sorted(zip(Z, Y, X), key=lambda x: (x[0], x[1]))]
['d', 'h', 'b', 'i', 'f', 'a', 'c', 'e', 'g']
Upvotes: 4