'Arrays in python, arrays won't line up, ( a beginner to coding)
I am trying to code some arrays in python, but when I run the code below, the "sort" and "people" lists won't line up properly ie. the sort is showing the wrong people. I am quite new to python so please keep code simple thanks. I know a lot of the code is repeated, but I am working on it. The problem area is mostly the last 3 lines but i have attached the rest, just to be sure.
people = []
score = []
people.append("Doc")
people.append("Sarah")
people.append("Jar-Jar")
Doc1 = int(input("Enter the test score for Doc "))
print("Test score:", Doc1)
Sarah1 = int(input("Enter the test score for Sarah "))
print("Test score:", Sarah1)
Jar1 = int(input("Enter the test score for Jar-Jar "))
print("Test score:", Jar1)
score.append(Doc1)
score.append(Sarah1)
score.append(Jar1)
sort = sorted(score, reverse = True)
print("[",sort[0],", '", people[0],"']")
print("[",sort[1],", '", people[1],"']")
print("[",sort[2],", '", people[2],"']")
Solution 1:[1]
Make tuples out of the scores and names so you can keep them together, and put those in a list; then just sort the list.
people = ["Doc", "Sarah", "Jar-Jar"]
scores = [
(int(input(f"Enter the test score for {person} ")), person)
for person in people
]
scores.sort(reverse=True)
for score, person in scores:
print(f"[{score}], '{person}'")
Enter the test score for Doc 1
Enter the test score for Sarah 4
Enter the test score for Jar-Jar 3
[4], 'Sarah'
[3], 'Jar-Jar'
[1], 'Doc'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
