YohanRoth
YohanRoth

Reputation: 3253

Arrange an array based on sorting re-arrangement of another

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

Answers (2)

John Coleman
John Coleman

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

rafaelc
rafaelc

Reputation: 59274

Using numpy

names[np.argsort(scores)]

assuming names is a numpy array. If not, just make it

names = np.array(names)

Upvotes: 2

Related Questions