如何使用Python3制作自动分级器

时间:2017-04-02 13:15:10

标签: python list python-3.x

我是编码的初学者。 我正在努力让学生评分,每个学生的名字将与每个年级的平均成绩相对应,并显示学生的总平均分数。 这是我的代码:

Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]

list1 = [Ken,Hiro,Nick]

total_average = 0
for j in list1:
   x = 0
   count = 0
   for i in j:
       x += i
       count += 1

   average = x / count
   print (round(average,2))
   total_average += average

final_average = total_average / len(list1)
print (round(final_average,2))

结果是:

7.33
13.67
20.0
13.67

但是,我实际上想要生成如下代码:

13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}

我怎么能这样表达呢?

如果你能解释一下细节,我们将不胜感激!

3 个答案:

答案 0 :(得分:1)

尝试使用字典而不是列表。 初始化字典: 学生= {' Hiro':0,' Ken':0,' Nick':0}

然后根据计算的平均值分配值: 学生= {' Hiro':20.0,' Ken':13.67,' Nick':13.67}

打印(学生)

答案 1 :(得分:1)

我建议用{name, scores, average_score}代表学生作为字典。您的所有学生都将成为词典列表:

students = [
    {'name': 'Ken', 'scores': [5, 8, 9], 'average_score': 0.0},
    {'name': 'Hiro', ...},
    ...
]

现在你会像这样迭代它们:

for student in students:
    # Access the attributes like this:
    print(student['name'], student['scores'])

    # calculate your average value ...

    student['average_value'] = x/count
print(students) # you can print the whole dictionary and look at the results

将学生全部放入列表中,可以轻松完成所需的格式化 - 只需循环浏览所有学生,并按照您想要的顺序打印他们的姓名和平均分数。

答案 2 :(得分:1)

我会建议另一种方法。首先,您将姓名和成绩存储在字典中:

grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}

然后,您循环遍历字典并计算每个学生的平均值并准备计算全球平均值:

averages = {}
sum_of_grades, number_of_grades = 0, 0
for name, marks in grades.items():
    averages[name] = sum(marks) / len(marks) # simple arithmetic average
    sum_of_grades += sum(marks)
    number_of_grades += len(marks)

最后,您计算全球平均值:

final_average = sum_of_grades / number_of_grades

这是完整的代码,其中计算封装在函数中:

grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}

def compute_averages(grades):
    averages = {}
    sum_of_grades, number_of_grades = 0, 0
    for name, marks in grades.items():
        averages[name] = sum(marks) / len(marks)
        sum_of_grades += sum(marks)
        number_of_grades += len(marks)
    final_average = sum_of_grades / number_of_grades

    return averages, final_average

averages, final_average = compute_averages(grades)
for name, avg in averages.items():
    print(name, round(avg, 2))
print('Final average', round(final_average, 2))