[英]Python: How to read from file of numbers (scores) use as list and get high score, low, and average score, and group into deciles
好吧,我需要這個問題的幫助,這是我上大學的最后一個項目,我不是csc專業,所以我真的只需要一些幫助! 我需要從隨機數文件中讀取並找到最大值,最小值和平均值。 然后將0分到100分之間的每十分位數(10%)分為幾組。 不確定為什么我的代碼沒有運行,到目前為止,我僅嘗試獲取最小值,最大值和平均值。
我已經在閱讀文件列表中尋求幫助,但是很多解決方案包括某種類型的“ with”循環事物,我還沒有學到。 另外,還在考慮可能具有單獨的功能/方法進行排序,然后再進行百分比/星級排序。 感謝您的任何幫助!
輸出示例:
高分是:100
最低的分數是:0
平均是:55.49
范圍編號百分比
========================================
0-9 75 7.5%*******
10-19 82 8.2%********
等等....
輸入文件是一個.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 % ***
有一些方便的dandy工具用於python中的數據處理。 我建議使用pandas
,因為它只需一個函數調用就可以完成很多工作。
import pandas as pd
import numpy as np
df = pd.read_csv("OldScores.txt", header=None, names=["scores"])
high_score = df["scores"].max()
low_score = df["scores"].min()
mean_score = df["scores"].mean()
median_score = df["scores"].median()
counts, divisions = np.histogram(df["scores"], bins=list(range(0,101,10)))
relative_counts = counts/df["scores"].shape[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.