如何在此代码中打印最后三个值的平均值?

时间:2018-11-02 07:33:01

标签: python python-3.x

这是代码

for i in range(0, len(my_list), 6):  
    print(my_list [i] + " " + my_list [i+1] + " - " + my_list [i+2] + " - " + my_list [i+3] + " , " + my_list [i+4] + " , " + my_list [i+5])

因此该代码获取一个文件,并以这种格式将文件中的6行打印为一行:

Marilyn Munro - 65783234 - 66, 77, 89
Johnny Lang - 83492753 - 45, 65, 45

我希望代码对最后三个数字求平均,以便输出结果如下:

James Hanniburg - 359372932 - 50, 75, 100

对此:

James Hanniburg - 359372932 - 81.25 #81.25 being the average of 50, 75, and 100, assuming 100 is worth 50%, and 50 and 75 are each worth 25%.

编辑:我忘了提及,第三个值占50%,而另外两个值分别占25%。

任何线索?

3 个答案:

答案 0 :(得分:0)

您可以例如将您的代码修改为:

for i in range(0, len(ml), 6): 
    weighted_avg = sum([int(ml[i+3]), int(ml[i+4]), 2*int(ml[i+5])]) / 4
    print(ml[i] + " " + ml[i+1] + " - " + ml[i+2] + " - " + str(weighted_avg))

这将用summingint转换后的值(将最后一次重复计数乘以2)计算加权平均值,然后将结果除以4。 / p>

答案 1 :(得分:0)

尝试一下: (值权重已添加。)

my_list = ['James', 'Hanniburg', 359372932, 50, 75, 100] # just input

a, b, c, d, e, f = my_list
print('{0} {1} - {2} - {3}'.format(a,b,c,((d*0.25+e*0.25+f*0.5)/3)))

输出:

C:\Users\Desktop>py x.py
James Hanniburg - 359372932 - 22.916666666666668

您还可以 从统计数据中导入均值

my_list = ['James', 'Hanniburg', 359372932, 50, 75, 100]
from statistics import mean 
a, b, c, *d = my_list
print('{0} {1} - {2} - {3}'.format(a,b,c,mean(d)))

答案 2 :(得分:0)

    for i in range(0, len(my_list), 6):
        print("{} {} - {} - {}".format(my_list[i], my_list[i+1], my_list[i+2],((my_list[i+3]+my_list[4])*0.25+my_list[5]*0.5)/3))