如果没有for循环,如何实现计算加权平均值

时间:2015-10-10 04:04:23

标签: python list python-2.7 python-2.x

这是我的代码如下:

students = [{'name': 'Tom',
             'subjects': {'math': 50,
                          'english': 100,
                          'science': 72}},
            {'name': 'Alex',
             'subjects': {'math': 100,
                          'english': 90,
                          'science': 95}}]

weighting_coefficient = {'math': 2,
                         'english': 10,
                         'science': 8}

total = sum(weighting_coefficient.values())

for index, student in enumerate(students):
    subjects = student['subjects']
    weighting_score = 0
    for subject, score in subjects.items():
        weighting_score += weighting_coefficient[subject] * score
    students[index]['weighted_average'] = float(weighting_score)/total

print students

结果:

[{'name': 'Tom',
  'subjects': {'english': 100, 'math': 50, 'science': 72},
  'weighted_average': 83.8},
 {'name': 'Alex',
  'subjects': {'english': 90, 'math': 100, 'science': 95},
  'weighted_average': 93.0}]

我确定要完成计算,但如果我不使用foor-loop来执行此操作,是否可以使用这些代码?

2 个答案:

答案 0 :(得分:0)

我不知道你的意思"试图缩短程序" ..

但是如果你想在几行中做到这一点,一种方式如下: 定义计算加权平均值的函数c,并在for-loop上使用它。这样,循环只有一行

设置

students = [{'name': 'Tom',
             'subjects': {'math': 50,
                          'english': 100,
                          'science': 72}},
            {'name': 'Alex',
             'subjects': {'math': 100,
                          'english': 90,
                          'science': 95}}]

w = {'math': 2,
     'english': 10,
     'science': 8}
total = sum(weighting_coefficient.values())

def c(dic):
    return (dic['math']*w['math'] + dic['english']*w['english'] + dic['science']*w['science'])/float(total)

代码

for x in students: x['weighted_average'] = c(x['subjects'])

答案 1 :(得分:0)

感谢@Kevin Guan的精彩提示(帮助我推进了自己的“Python职业生涯”)

使用列表理解,如建议:

students = [{'name': 'Tom',
         'subjects': {'math': 50,
                      'english': 100,
                      'science': 72}},
        {'name': 'Alex',
         'subjects': {'math': 100,
                      'english': 90,
                      'science': 95}}]

weighting_coefficient = {'math': 2,
                     'english': 10,
                     'science': 8}

total = sum(weighting_coefficient.values())

for student in students:
    student['weighted_average'] = float( sum( [student['subjects'][subj] * weighting_coefficient[subj] for subj in student['subjects'].keys() ] ) ) / total

print students

代码看起来很乱,但您可以创建一些更多变量来保存关键信息(并使weighting_coefficients更短)。

我已经使用原始数据集和一个额外数据进行了测试(此处未包括但使用OP方法和我的方法匹配结果)。