无for循环加权平均计算的实现

2024-04-19 16:37:48 发布

您现在位置: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 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来实现代码,它是否可用?你知道吗


Tags: 代码nameenglishmathtotalsciencescoreaverage
1条回答
网友
1楼 · 发布于 2024-04-19 16:37:48

感谢@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的方法和我的方法匹配的结果)。你知道吗

相关问题 更多 >