首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从文本文件中按字母顺序排列名称和分数,该文本文件连接用户名和他们的最高得分。

从文本文件中按字母顺序排列名称和分数,该文本文件连接用户名和他们的最高得分。
EN

Stack Overflow用户
提问于 2016-03-17 13:06:39
回答 1查看 62关注 0票数 2
代码语言:javascript
运行
复制
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分,最后我也想打印用户的平均得分从最高到最低。

EN

Stack Overflow用户

回答已采纳

发布于 2016-03-17 17:10:22

如果我理解正确的话,这应该能回答你的问题。

代码语言:javascript
运行
复制
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)

输出:

代码语言:javascript
运行
复制
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
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36061440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档