Python-统计txt文件里面的分数
时间: 2023-08-14 15:27:31 浏览: 56
可以使用Python内置的文件操作和数据统计函数来实现统计txt文件里面的分数。
假设txt文件中每行都是一个分数,可以按照行读取文件并将每个分数存储到一个列表中,然后使用Python内置的统计函数进行分数的统计。
以下是一个示例代码:
``` python
# 打开文件
with open('scores.txt', 'r') as f:
# 读取文件并将每个分数存储到列表中
scores = [int(line.strip()) for line in f.readlines()]
# 统计分数的数量、平均分和总分
num_scores = len(scores)
avg_score = sum(scores) / num_scores
total_score = sum(scores)
# 打印统计结果
print('分数数量:', num_scores)
print('平均分:', avg_score)
print('总分:', total_score)
```
其中,`scores.txt` 是包含分数的txt文件名,可以根据实际情况进行修改。
相关问题
Python-统计txt文件里面的分数,名字
如果txt文件中每行包含分数和名字,可以使用Python的正则表达式模块re来提取分数和名字,并将它们存储到一个字典中,然后使用Python内置的统计函数对分数进行统计。
以下是一个示例代码:
``` python
import re
# 打开文件
with open('scores.txt', 'r') as f:
# 读取文件并将每个分数和名字存储到字典中
scores_dict = {}
for line in f.readlines():
match = re.match(r'(\d+)\s+(.+)', line.strip())
if match:
score = int(match.group(1))
name = match.group(2)
scores_dict[name] = score
# 统计分数的数量、平均分和总分
num_scores = len(scores_dict)
avg_score = sum(scores_dict.values()) / num_scores
total_score = sum(scores_dict.values())
# 打印统计结果
print('分数数量:', num_scores)
print('平均分:', avg_score)
print('总分:', total_score)
```
其中,`scores.txt` 是包含分数和名字的txt文件名,可以根据实际情况进行修改。
python统计各个分数段的人数
Python是一种功能强大的编程语言,提供了丰富的工具来进行数据分析和处理,可以轻松实现统计各个分数段的人数。具体步骤如下:
1. 首先,读取包含分数数据的文件,可以使用Python内置的open函数打开文件,再使用readlines函数将文件内容读取为一个字符串列表。
2. 然后,可以使用split函数将每个学生的分数拆分为一个个字符串,并将字符串转换为整数类型,存储到一个分数列表中。
3. 接着,根据需求,将分数进行分类,可以使用Python内置的if语句进行条件判断,将符合不同条件的分数保存到不同的列表中。
4. 最后,通过统计每个列表中元素的数量,即可得到每个分数段的人数。
下面是一个Python示例代码:
```python
# 打开包含分数数据的文件
with open('scores.txt', 'r') as f:
lines = f.readlines()
# 将分数字符串转换为整型
scores = [int(x) for x in ''.join(lines).split()]
# 分类统计分数
score_0_60 = []
score_60_70 = []
score_70_80 = []
score_80_90 = []
score_90_100 = []
for score in scores:
if score < 60:
score_0_60.append(score)
elif score < 70:
score_60_70.append(score)
elif score < 80:
score_70_80.append(score)
elif score < 90:
score_80_90.append(score)
else:
score_90_100.append(score)
# 统计各个分数段的人数
print('0~60分人数:', len(score_0_60))
print('60~70分人数:', len(score_60_70))
print('70~80分人数:', len(score_70_80))
print('80~90分人数:', len(score_80_90))
print('90~100分人数:', len(score_90_100))
```
通过上述代码,就可以轻松地统计各个分数段的人数了。