Reputation: 3253
I have two arrays names
and scores
. Every index in names
correspond to an index in scores
. How do I arrange names
in the order that corresponds to sorted scores
?
E.g from
names = ["Jo", "Mary", "Luke"]
scores = [9, 4, 8]
we get
scores = [4, 8, 9]
names = ["Mary", "Luke", "Jo"]
I have only one ugly idea is to first convert 2 arrays into array of tuples and then use standard python sort and then convert back into two arrays. Are there any nice way without ugly for loops and double conversion?
Thanks
Upvotes: 0
Views: 66
Reputation: 51998
Could use:
[name for score,name in sorted(zip(scores,names))]
Logically, this is similar to the double-conversion approach you describe, but the use of zip
and comprehensions achieves it in one line with no explicit looping.
Upvotes: 1