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穆罕默德5鲍勃4鲍勃7迈克尔2迈克尔8詹姆斯7詹姆斯6托尼7托尼4托尼4萨拉6我希望能够打印出用户的最高分,然后我想打印用户的得分从最高到最低,因为穆罕默德先得到10分,最后我也想打印用户的平均得分从最高到最低。
发布于 2016-03-17 17:10:22
如果我理解正确的话,这应该能回答你的问题。
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
https://stackoverflow.com/questions/36061440
复制相似问题