I have two lists
X = ["a", "b", "c", "d"]
Y = [3, 1, 5, 2]
and want to sort the list X
to
X = ["c", "a", "d", "b"]
based on descending values of items in list Y
in the corresponding positions
I have two lists
X = ["a", "b", "c", "d"]
Y = [3, 1, 5, 2]
and want to sort the list X
to
X = ["c", "a", "d", "b"]
based on descending values of items in list Y
in the corresponding positions
Tuples, by default, are ordered by the first value.
So zip the lists with Y
's items first, sort it (reversed) and then extract the second item (X
):
>>> sorted_list = [item[1] for item in sorted(zip(Y, X), reverse=True)]
>>> sorted_list
['c', 'a', 'd', 'b']
>>>
You can use a dictionary to keep the mapping and then do the sort:
>>> X
['a', 'b', 'c', 'd']
>>> Y
[3, 1, 5, 2]
>>> d = dict(zip(X, Y))
>>> sorted(X, key=lambda x: d[x], reverse=True)
['c', 'a', 'd', 'b']
X = ["a", "b", "c", "d"]
Y = [3, 1, 5, 2]
zipped = zip(Y,X)
zipped.sort()
print zipped
[(1, 'b'), (2, 'd'), (3, 'a'), (5, 'c')]