Shortest Code
[x for _, x in sorted(zip(Y, X))]
Example:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Z = [x for _,x in sorted(zip(Y,X))]
print(Z) # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Generally Speaking
[x for _, x in sorted(zip(Y, X), key=lambda pair: pair[0])]
Explained:
zip
the two list
s.
- create a new, sorted
list
based on the zip
using sorted()
.
- using a list comprehension extract the first elements of each pair from the sorted, zipped
list
.
For more information on how to setuse the key
parameter as well as the sorted
function in general, take a look at this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…