gpt4 book ai didi

python - 用特定公式取加权平均

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:41 25 4
gpt4 key购买 nike

infileName="grades.txt"
infile=open(infileName,"r")
outfileName="weightedavg.txt"
outfile=open(outfileName,"w")
for line in infile:
test=line.strip()
test=line.split()
fname=test[0]
lname=test[1]
grades=test[3::2]
weights=test[2::2]
grades=[int(i) for i in grades]
weights=[int(i) for i in grades]
weightedavg=????

The formula for the weighted average is (weight1*grade1)+(weight2*grade2)...+ (weightn+graden)

最佳答案

您可以将两个列表压缩在一起,将每个对应的元素相乘并求和:

print(sum(a*b for a,b in zip(weights, grades)))

这假定两个列表的长度相同,但我想它们是相同的,或者您的逻辑是错误的。

我不确定我是否遵循了您的所有代码,因为您似乎在循环但不在循环外存储成绩或权重,因此我假设您希望对每一行执行此操作:

infileName="grades.txt"
outfileName="weightedavg.txt"

with open(infileName) as infile, open(outfileName,"w") as outfile:
for line in infile:
test = line.split()
grades = map(int,test[3::2])
weights = map(int,test[2::2])
wghtd_avg = sum(a*b for a,b in zip(weights,grades))

如果除了计算之外不需要等级或权重,您可以将 mapitertools.islice 一起使用:

from itertools import islice

with open(infileName) as infile, open(outfileName,"w") as outfile:
for line in infile:
test = line.split()
it = map(int, islice(test, 2, None)) # itertools.imap for python2
print(sum(a*b for a,b in zip(it, it)))

使用 with 会自动关闭您的文件,如果您使用的是 python2,请使用 itertools.imapitertools.izip

关于python - 用特定公式取加权平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29401604/

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