python - Python:如何从数字文件中读取(分数)用作列表并获得高分、低分和平均分,并将其分组为十分位
问题描述
好的,我需要帮助解决这个问题,这是我大学的最后一个项目,我不是 csc 专业的,所以我真的只需要一些帮助!我需要从随机数文件中读取并找到最大值、最小值和平均值。然后从 0 到 100 对每个(10%)十分位的分数进行分组。不知道为什么我的代码没有运行,到目前为止我只尝试获取最小值、最大值和平均值。
我一直在寻找有关阅读文件以列出问题的帮助,但很多解决方案都包括某种类型的“with”循环,我还没有学过。此外,正在考虑可能有单独的功能/方法进行排序,然后是百分比/星号。感谢您的任何帮助!
示例输出:
最高分是:100
最低分是:0
平均值为:55.49
范围数百分比
==========================================
0-9 75 7.5% *******
10-19 82 8.2% ********
ETC....
输入文件是一个 .txt 文件,每个分数都在一个新行上。
33 99 14 52
76
78
This is the error that comes out:
Traceback (most recent call last):
File "/Users/meganhorton/Desktop/Python/hw5.py", line 36, in <module>
main()
File "/Users/meganhorton/Desktop/Python/hw5.py", line 20, in main
avgScore = float(sum(scoresList)/len(scoresList))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
解决方案
这是使用纯 Python 解决问题的另一种方法:
with open("scores.txt", "r") as inFile:
scores = [int(line) for line in inFile]
maximum = max(scores)
minimum = min(scores)
average = sum(scores) / len(scores)
deciles = [0 for i in range(10)]
for score in scores:
for i in range(0,100,10):
if score in range(i, i+10):
deciles[int(i/10)] += 1
print("The high score is: %d" % maximum)
print("The low score is: %d" % minimum)
print("The average is: %.2f" % average)
print("=========================================")
for i in range(10):
print("%d - %d" % (i*10, i*10+9), end=" ")
print(deciles[i], end=" ")
print("%.2f %s" % (((deciles[i] / sum(deciles)) * 100.0), "%"), end=" ")
print("*" * deciles[i])
您提供的示例数据的输出:
The high score is: 98
The low score is: 18
The average is: 66.83
=========================================
0 - 9 0 0.00 %
10 - 19 1 16.67 % *
20 - 29 0 0.00 %
30 - 39 0 0.00 %
40 - 49 1 16.67 % *
50 - 59 1 16.67 % *
60 - 69 0 0.00 %
70 - 79 0 0.00 %
80 - 89 0 0.00 %
90 - 99 3 50.00 % ***
推荐阅读
- php - Db Insert 在安装模块期间在 Prestashop 1.7 中返回 false
- javascript - 过滤表依赖于多选标签
- node.js - 如何使用 browserify 将 script.js 文件更改为 bundel.js 文件?
- regex - 检查正则表达式模式是否受长度限制
- python - 将 one_hot_encoding 0/1 替换为其他列中的值
- android - 是否可以使匕首应用程序组件无效并在android中创建一个新的匕首应用程序组件
- c# - 带有 group by 和有子句的 Linq 语法
- jooq - Jooq-将字段更新为 NULL 使其“null”而不是 NULL
- python - 使用 selenium Virustotal 上传文件
- c# - 如何使用 Entity Framework Core 搭建 SQL 同义词?