首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在没有for循环的情况下如何实现加权平均

在没有for循环的情况下如何实现加权平均
EN

Stack Overflow用户
提问于 2015-10-10 04:04:23
回答 1查看 222关注 0票数 0

以下是我的代码:

代码语言:javascript
复制
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

结果:

代码语言:javascript
复制
[{'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来实现代码,是否可用呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-10 04:50:57

谢谢你给我的好建议(帮我推进了我自己的"Python事业“)

使用列表理解,如建议的:

代码语言:javascript
复制
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的方法和我的方法匹配的结果)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33050139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档