Zak
Zak

Reputation: 43

How do I align two arrays after I've sorted 1 one of them?

I have two list which their values match with each others positions. So Jon's score would be 123 and Bede's would be 11 etc.

name = ["Jon", "Bede", "Joe"]
score = [123, 11, 43]

How is it possible to order the the list so that it outputs the smallest score first ascending to the highest score, each time outputting the name of the person who scored it.

Upvotes: 0

Views: 963

Answers (6)

Stef
Stef

Reputation: 15505

You can use zip(...) to aggregate the two lists together; then sort; then use zip(*...) to unzip the result.

name = ["Jon", "Bede", "Joe"]
score = [123, 11, 43]
newscore, newname = map(list, zip(*sorted(zip(score, name))))
print(newname)
print(newscore)
# ['Bede', 'Joe', 'Jon']
# [11, 43, 123]

Upvotes: 0

Remi Guan
Remi Guan

Reputation: 22282

What about this one?

name = ["Jon", "Bede", "Joe"]
score = [123, 11, 43]

for i in sorted(zip(name, score), key=lambda x:x[1]):
    print(i[0], i[1], sep=': ')

Output:

Bede: 11
Joe: 43
Jon: 123

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49310

Instead of sticking with a pair of parallel lists, try turning them into a dictionary for easier access. You can then sort the dictionary by its keys with the key argument:

name = ["Jon", "Bede", "Joe"]
score = [123, 11, 43]
results = dict(zip(name, score))
for k in sorted(results, key=results.get):
    print('{}: {}'.format(k, results[k]))

Result:

Bede: 11
Joe: 43
Jon: 123

Upvotes: 0

Daniel
Daniel

Reputation: 42758

If you have two lists, where the indices are correlated, it is very difficult to keep them in sync. The solution python has, is one list of tuples, where the first element in each tuple is the name and the second one is the score:

names_with_score = [
    ("Jon", 123),
    ("Bede", 11),
    ("Joe", 43),
]
names_with_score.sort(key=lambda x: x[1]) # sort with the second element

If you have no control over how the data is delivered, you might join to lists with the zip-function:

names_with_score = zip(name, score)

Upvotes: 1

dopstar
dopstar

Reputation: 1488

for s, n in sorted(zip(score, name)): # sort by score.
    print(n, s)

Upvotes: 5

Jameson
Jameson

Reputation: 6659

This merges the lists, if you don't mind that:

sorted(zip(name,score))

Upvotes: 0

Related Questions