Let’s consider the following two lists…
X = ["a", "b",
"c", "d", "e", "f", "g",
"h", "i"]
Y = [ 0, 1,
1, 0, 1,
2, 2, 0,
1]
Now we would like to sort the list X
based on the list Y. The final sorted list X would look like the following…
["a", "d",
"h", "b", "c", "e", "i",
"f", "g"]
Solution…
- · zip the two lists.
- · 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.
[x for _, x in
sorted(zip(Y,X), key=lambda pair: pair[0])]
No comments:
Post a Comment