Reputation: 63
if Class.lower() == ("classa"):
from collections import defaultdict #Automatically creates an empty list
scores = defaultdict(list)#Creates the variable called scores
with open('ClassA.txt') as f:#Opens the text file for classA
for score, name in zip(f, f):#Makes the users
scores[name.strip()].append(int(score))#Appends scores to a list as you cant have the same key twice in a dictionary.
the text file looks like this: 10 Mohammad 8 Mohammad 9 Mohammad 5 Bob 4 Bob 7 Bob 3 Micheal 2 Micheal 5 Micheal 8 James 6 James 7 James 6 Tony 4 Tony 7 Tony 4 Sara 6 Sara 6 I would like to be able to print the users highest score from the three scores then i would like to print the users scores from highest to lowest e.g mohammad first since he got 10 points and then finally i would also like to print the users scores by average from highest to lowest.
Upvotes: 2
Views: 64
Reputation: 30
This should answer you question if I understood it correctly.
import re
for score, name in re.findall("(\d+) (\w+)", f.read()): # using regular expressions module to parse the scores and names
scores[name.strip()].append(int(score))
# Set highest scores first in list and print those sorted
# sort the individual scores high to low, list format[(name, scores),...,]
score_list = [(name, sorted(scores[name], reverse=True)) for name in scores]
# sort the named scores high to low by highest score(x[0] sorts names alphabetic)
score_list = sorted(score_list, key=lambda x: x[1], reverse=True)
print("Highest sorted")
for name, v in score_list: # v contains the individual scores
print(v[0], name) # Print highest score which is at 0 index and print the name
print()
print("highest to lowest")
for name, v in score_list: # v contains the individual scores
print(v, name) # Print scores and name
print()
print("highest average")
average_scores = []
# iterate through the ordered score list and append the average score to the average_scores list
for name, v in score_list: # v contains the individual scores
average_scores.append((name, sum(v) / len(v)))
# sort average_scores high to low
sorted_average_scores = sorted(average_scores, key=lambda x: x[1], reverse=True)
# iterate through sorted_average_scores and print the rounded average, non-sorted individual scores, and name
for name, average in sorted_average_scores:
print(round(average), scores[name], name)
Output:
Highest sorted
10 Mohammad
8 James
7 Tony
7 Bob
6 Sara
5 Micheal
highest to lowest
[10, 9, 8] Mohammad
[8, 7, 6] James
[7, 6, 4] Tony
[7, 5, 4] Bob
[6, 4] Sara
[5, 3, 2] Micheal
highest average
9 [10, 8, 9] Mohammad
7 [8, 6, 7] James
6 [6, 4, 7] Tony
5 [5, 4, 7] Bob
5 [4, 6] Sara
3 [3, 2, 5] Micheal
Upvotes: 1