学生在python中的平均成绩和科目的成绩平均计算器

时间:2017-06-01 07:18:31

标签: python

我在python中制作一个计算器,它给了我学生的平均成绩和平均成绩。 下面是我需要输入以及输出应该如何显示的图片。

我正在尝试使用嵌套列表和函数。我试过这个。

2 个答案:

答案 0 :(得分:0)

您可以使用while循环和Pandas

轻松完成此操作
import pandas

list_marks = {}

subjects = int(input("Number of subjects: "))

while(True):
    name = input("Name of student (leave empty if finished): ")
    if not name:
        break

    scores = []
    for i in range(1, subjects + 1):
        scores.append(int(input("Subject %d: " % i)))

    list_marks[name] = scores

scores = pandas.DataFrame(list_marks)
print(scores)
#     student1  student2  student3
# 0       100        90        80
# 1       100        90        60
print(scores.mean(axis=0))
# student1    100.0
# student2     90.0
# student3     70.0
# dtype: float64
print(scores.mean(axis=1))
# 0    90.000000
# 1    83.333333
# dtype: float64

或使用NumPy:

import numpy

scoresarray = numpy.array(list(list_marks.values()))
print(numpy.mean(scoresarray, axis=0))
# [ 90.          83.33333333]
print(numpy.mean(scoresarray, axis=1))
# [ 100.   90.   70.]

答案 1 :(得分:0)

试试此代码

  def calc(student_count):
        list_marks = []
        for i in range(int(student_count)):
            student_name = input("name of student?")
            sub1_score = input("Score of subject 1?")
            sub2_score = input("Score of subject 2?")
            average = (int(sub1_score) + int(sub2_score))/2
            list_marks.append([student_name,sub1_score,sub2_score,average])
        print (list_marks)
        return list_marks                    


    no_of_students = input("How many students?")
    #no_of_subjects = input("How many subjects?")
    calc(no_of_students)  

这将产生两个科目所需的输出。

如果您有很多科目,请将它们相加并除以其计数