python - 从txt读取分数并显示最高分数和记录
问题描述
从 Python第 6 章开始练习:
- 高分 假设计算机磁盘上存在一个名为 scores.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()
希望对你有帮助:)
推荐阅读
- html - 当有图像时,jQuery问题仅从表格单元格中选择文本
- swift - dyld:未加载库:在实际 iPhone 上安装时
- c++ - 使用具有自动范围和结构化绑定的 C++ 迭代向量矩阵?
- javascript - 我试图访问 DOM 中无线电输入的名称属性,但显然所有名称字段的值都为 false?
- regex - NiFi - 使用先前属性 + 硬编码文本创建新属性的新属性
- c++ - std 线程构造函数是否采用可变线程函数?
- java - FAB on click 根据当前显示的片段开始新活动
- c++ - MSVC 编译器尝试调用已删除的复制构造函数,而不是移动地图元素
- django - 正确的日志配置以禁用 django 错误电子邮件
- c++ - 滥用指针会产生分段错误。我仍然不确定如何纠正它