Legend Legend -4 years ago 87
Python Question

Sorting list based on values from another list?

I have a list of strings like this:

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]


What is the shortest way of sorting X using values from Y to get the following output?

["a", "d", "h", "b", "c", "e", "i", "f", "g"]


The order of the elements having the same "key" does not matter. I can resort to the use of
for
constructs but I am curious if there is a shorter way. Any suggestions?

Answer Source
[x for (y,x) in sorted(zip(Y,X))]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download