从txt读取分数并显示最高分数和记录

六边形

从 Python第 6 章练习开始:

  1. 高分 假设计算机磁盘上存在名为 score.txt 的文件。它包含一系列记录,每个记录有两个字段 - 一个名称,后跟一个分数(1 到 100 之间的整数)。编写一个程序,显示得分最高的记录的名称和分数,以及文件中的记录数。(提示:使用变量和“if”语句来跟踪阅读记录时找到的最高分,并使用变量来记录记录数。)
Data in grades.txt
Jennifer 89
Pearson 90
Nancy 95
Gina 100
Harvey 98
Mike 99
Ross 15
Test 90

file=open('grades.txt','r')
my_list=[]

num_of_records=0
highest_score=1
highest_score_name=''

for line in file:
    name,score=line.strip().split()
    if int(score)>highest_score:
        highest_score=int(score)
        highest_score_name=name

    num_of_records=num_of_records+1


print('the name and score of the record with highest score:')
print('Name:',highest_score_name)
print('Score:',highest_score)

print('\nNumber of records:',num_of_records)

file.close()

这里是 python 的入门者,并试图通读这本书,但是在这个问题上遇到了错误。

错误:

line 9, in <module> name,score=line.strip().split() 
  ValueError: not enough values to unpack (expected 2, got 0)

任何指南表示赞赏。

舒巴姆·夏尔马

好的,发生的事情实际上是您的数据在文件末尾有一个换行符,当您尝试拆分时会导致错误。这是正确的代码:

file = open('grades.txt', 'r')

num_of_records = 0
highest_score = 1
highest_score_name = ''

for line in file:
    line = line.strip()
    # Check whether the line is empty
    if line == '':
        continue

    name, score = line.split()
    if int(score) > highest_score:
        highest_score = int(score)
        highest_score_name = name

    num_of_records = num_of_records+1


print('the name and score of the record with highest score:')
print('Name:', highest_score_name)
print('Score:', highest_score)

print('\nNumber of records:', num_of_records)

file.close()

希望对你有帮助:)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在单个查询中显示分数和最高分数

JS-显示最高分数和与该分数相关的名称

获得最高分数和获胜次数

从数组列表中获取并显示最高分数和名称

在表格中显示职员名称,主题名称和最高分数

贪婪算法以获得最高分数

每年寻找最高分数

用最高分数打印学生

如何从Redis的SortedSet中获得最高分数(分数和成员)?

排序值并获取最佳分数(最高分数)

排序值并获取最佳分数(最高分数)

按最高分数排序.txt文件不起作用

如何显示每个部门的最高分数及其名称

接受名称和 10 个分数并返回名称和 6 个最高分数的 Python 程序

如何优化最小和最大以找到最高分数总和

为什么不打印单个玩家的最高分数?

获取每次测试最高分的 AVG 分数

在最高分数上添加特定点

联系名人堂(团体玩家,当月为...时,每个游戏的最高等级和最高分数)

使用循环从列表中找到最高分数,最低分数

显示txt文件中arrayList的最高分

在MySQL中进行比较后如何获得最高分数

熊猫:添加新列,其中包含该人一天达到最高分数的频率

如何从此表中的每个不同用户中选择最高分数?

根据最高分数过滤数组中的用户名

使用python在图中找到最高分数路径的函数

获取每个玩家根据日期获得最高分数的次数

获取最高分数并存储在另一列中

Django-如何获得前10名最高分数,但将其限制为每位用户一个分数?