编程题/1.final123-将文件中的一组成绩转换为五级制 【问题描述】 在文件in.txt中, 存放有一组0至100以内的整数(代表百分制的成绩), 数据之间用空格隔开,读取文件内容 按下面列出的规则将成绩转换为五级制 100至90优秀 89至80良好79至70中等 69至60及格 小于60不及格 并统计每个等级的人数, 将结果输出到文件out.txt中 文件中先写入五级制成绩(成绩之间用空格隔开), 再换行,写入表头'等级\t人数\t占比 再按等级由高到低的顺序, 每行写入一个等级、相应的人数和占比,(若某等级人数为0,则忽略)
时间: 2023-12-14 21:40:07 浏览: 44
以下是Python的实现代码:
```python
# 读取文件内容
with open('in.txt', 'r') as f:
scores = list(map(int, f.read().split()))
# 将百分制成绩转换为五级制
levels = ['优秀', '良好', '中等', '及格', '不及格']
level_counts = [0, 0, 0, 0, 0]
for score in scores:
if score >= 90:
level_counts[0] += 1
elif score >= 80:
level_counts[1] += 1
elif score >= 70:
level_counts[2] += 1
elif score >= 60:
level_counts[3] += 1
else:
level_counts[4] += 1
# 计算占比
total_count = sum(level_counts)
level_percents = [count/total_count for count in level_counts]
# 写入文件
with open('out.txt', 'w') as f:
# 写入五级制成绩
level_scores = [f'{level}:{count}' for level, count in zip(levels, level_counts)]
f.write(' '.join(level_scores) + '\n')
# 写入表头
f.write('等级\t人数\t占比\n')
# 写入每个等级的人数和占比
for level, count, percent in zip(levels, level_counts, level_percents):
if count > 0:
f.write(f'{level}\t{count}\t{percent:.2%}\n')
```
假设in.txt中的内容为:`78 92 85 60 45 70 80 88 93 71 89`
则out.txt中的内容应该为:
```
优秀:3 良好:3 中等:2 及格:2 不及格:1
等级 人数 占比
优秀 3 27.27%
良好 3 27.27%
中等 2 18.18%
及格 2 18.18%
不及格 1 9.09%
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)