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=????



  加权平均值的公式是(weight1 * grade1)+(weight2 * grade2)... +(weightn + graden)

最佳答案

生成器表达式(您可以将其视为隐式列表理解)可能是最“ 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

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

10-12 13:59