[英]Trying to calculate the average of a float list?
I don't know if I'm going about getting the float
values the right way but this is what I have so far.我不知道我是否打算以正确的方式获取float
值,但这是我目前所拥有的。
grades_file = open('grades.txt', 'r')
# Print Header & spacer
print('Name' + '\t\tGrade')
print('---------------------')
# Read lines & store grades
for file_lines in grades_file:
lines = file_lines.rstrip('\n')
num_list = re.findall(r"[-+]?\d*\.\d+|\d+", lines)
grades = [float(num) for num in num_list]
average = statistics.mean(grades)
print(lines)
print(average)
Now I'm trying to get it to print what's in the file and print the average of the numbers separately but this is what I'm getting.现在我试图让它打印文件中的内容并分别打印数字的平均值,但这就是我得到的。
Output:
Name Grade
---------------------
Mickey,Mouse 90.0
90.0
Jane,Doe 50.0
50.0
Minnie,Mouse 95.0
95.0
Donald,Duck 80.0
80.0
Daffy,Duck 70.0
70.0
What am I doing wrong here?我在这里做错了什么?
Edit: The contents of num_list
:编辑: num_list
的内容:
['90.0']
['50.0']
['95.0']
['80.0']
When I try to just print num_list
it shows up similar to printing average.当我尝试只打印num_list
时,它显示为类似于打印平均值。
Contents of the input file:输入文件的内容:
Mickey,Mouse 90.0
Jane,Doe 50.0
Minnie,Mouse 95.0
Donald,Duck 80.0
Daffy,Duck 70.0
I managed to figure it out.我设法弄明白了。 I don't know why but I had to put the grade average in a separate function我不知道为什么,但我不得不将平均成绩放在一个单独的 function 中
def grade_avg():
grades_file = open('grades.txt', 'r')
file_contents = grades_file.read()
num_list = re.findall(r"[-+]?\d*\.\d+|\d+", file_contents)
grades = [float(num) for num in num_list]
average = mean(grades)
print('Average Grade:', average)
It seems like a long workaround but it works.这似乎是一个漫长的解决方法,但它确实有效。
You are using the regex
function inside the for loop
of each line of the file.您在文件每一行的for loop
内使用regex
function。 So you are calculating the average of a single number.因此,您正在计算单个数字的平均值。
You need to calculate the average first, and then print each line contents:您需要先计算平均值,然后打印每行内容:
import re
import statistics
with open('grades.txt', 'r') as grades_file:
# Print Header & spacer
print('Name' + '\t\tGrade')
print('---------------------')
num_list = re.findall(r"[-+]?\d*\.\d+|\d+", grades_file.read()) #get all grades from file
grades = list(map(float, num_list)) #convert to float
average = statistics.mean(grades) #compute average
# Read lines & store grades
grades_file.seek(0) #reset file position
for file_lines in grades_file:
lines = file_lines.rstrip('\n')
print(lines)
print(average)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.