用特定公式取加权平均

Taking weighted avg with specific formula

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

生成器表达式(您可以将其视为隐含的列表理解)可能是最"Pythonic" 的解决方案:

grades = [83, 92, 96]
weights = [0.4, 0.4, 0.2]
weighted_avg = sum(x * y for x,y in zip(grades, weights))

最后,weighted_avg == 89.2