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.
文本文件如下所示: 10 穆罕默德 8 穆罕默德 9 穆罕默德 五 短发 4 短发 7 短发 3 迈克尔 2 迈克尔 五 迈克尔 8 詹姆士 6 詹姆士 7 詹姆士 6 托尼 4 托尼 7 托尼 4 萨拉 6 萨拉 6 我希望能够从三个分数打印用户最高分然后我想打印用户分数从最高到最低,例如穆罕默德,因为他得到10分然后最后我还要打印用户分数从最高到最低的平均值。
答案 0 :(得分:1)
如果我理解正确,这应该回答你的问题。
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)
输出:
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