gpt4 book ai didi

python - 如何获得学期平均分

转载 作者:行者123 更新时间:2023-12-01 00:01:20 24 4
gpt4 key购买 nike

我的代码将采用成绩图例和成绩数,然后返回它的值。除了学期平均分外,我一切都好。以下是计算学期平均分的公式:

homework average * 0.2 + quiz average * 0.2 + project average * 0.6.

我的代码适用于家庭作业平均数、测验平均数和项目平均数,但不适用于学期平均数。这是我写的:

def get_header():  
gb_data = open('gb_data.txt','r')
header = gb_data.readline()
return header.strip()

def get_content():
gb_data = open('gb_data.txt','r')
content = gb_data.readlines()
del content[0]
return content

hw_pos = []
project_pos = []
quiz_pos = []

header_list = get_header()
header_list = header_list.split(", ")
header_list_index = enumerate(header_list)
for index, target in header_list_index:
if target == "hw":
hw_pos.append(index)
elif target == "quiz":
quiz_pos.append(index)
elif target == "project":
project_pos.append(index)

content_list = get_content()

avg_dict = {}

for element in content_list:
element = element.strip().split(", ")

name = element[0] + ', ' + element[1]
hw_avg = sum([int(element[i]) for i in hw_pos]) / len(hw_pos)
quiz_avg = sum([int(element[i]) for i in quiz_pos]) / len(quiz_pos)
project_avg = sum([int(element[i]) for i in project_pos]) / len(project_pos)
sem_avg = hw_avg * 0.2 + quiz_avg * 0.2 + project_avg * 0.6
avg_dict.update({name:(hw_avg, quiz_avg, project_avg, sem_avg)})


f = open('avg.txt', 'w')
for name, avg in avg_dict.items():
dataline = name + ": hw avg = " + str(round(avg[0], 2)) + ", quiz avg = " + str(round(avg[2], 2)) + ", proj avg = " + str(round(avg[1], 2)) + ", sem avg = " + str(round(avg[2], 2)) + "\n"
f.write(dataline)

f.close()

这是我输入的一个示例:

last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88

顶行是图例,所以忽略它,我的代码会处理它以下是应该返回的内容:

Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21

这是我实际得到的结果:

Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 96.0

我想让它们完全匹配,精确到每个字符。我只需要知道如何正确舍入它。这不是家庭作业,只是一个更好地理解文件的项目,我非常接近了!顺便说一句,我叫斯嘉丽,请帮忙!!!

最佳答案

这行有一个拼写错误:

dataline = name + ": hw avg = " + str(round(avg[0], 2)) + ", quiz avg = " + str(round(avg[2], 2)) + ", proj avg = " + str(round(avg[1], 2)) + ", sem avg = " + str(round(avg[2], 2)) + "\n"

应该是

dataline = name + ": hw avg = " + str(round(avg[0], 2)) + ", quiz avg = " + str(round(avg[1], 2)) + ", proj avg = " + str(round(avg[2], 2)) + ", sem avg = " + str(round(avg[3], 2)) + "\n"

相反。计算没问题,只是输出困惑了(您打印了 0, 2, 1, 2 而不是 0, 1, 2, 3)。为了防止将来出现类似的错误,也许可以看看 Pandas 及其列名?在这种情况下,Pandas 可能有点大材小用,但它是基于表格的计算的一个非常强大的工具。

关于python - 如何获得学期平均分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com