首页 > 解决方案 > 如何获取存储列表的平均年龄或等级

问题描述

我在获取列表中的值时遇到错误在获取列表中的平均值时输入的正确代码是什么


values = [["Name", 'Age', 'Grade']]

for i, val in enumerate(values):
 print(i, val)

while True:
   
  print("\n1 - Add\n2 - Show Report\n")
    
  choice = int(input("Enter your choice: "))
  
  if choice == 1:
   name = str(input("Input Name: "))
   age = int(input("Enter Age: "))
   grade = float(input("Enter Grade: "))
   values.append([name, age, grade])
   
   for i, val in enumerate(values):
    print(i, val)
  
  elif choice == 2:
   for i, val in enumerate(values):
    a = sum(val[1] / i)
    print("The average age in the list is", a)
    b = sum(val[2] / i)
    print("The average grade in the list is", b)
   

这应该是程序的输出
我应该添加一个代码来删除“年龄”并得到总和然后除法吗?
样本输出

0 ['Name', 'Age', 'Grade']

1 - Add
2 - Show

Enter your choice: 1
Input name: Bob
Input Age: 24
Input Grade: 90
0 ['Name', 'Age', 'Grade']
1 ['Bob', 24, 90.0]

1 - Add
2 - Show

Enter your choice: 1
Input name: Jun
Input Age: 20
Input Grade: 95
0 ['Name', 'Age', 'Grade']
1 ['Bob', 24, 90.0]
2 ['Jun', 20, 95.0]

1 - Add
2 - Show

Enter your choice: 2
The average age in the list is 22
The average grade in the list is 92.5

标签: python

解决方案


无需更改太多代码:

这是您的列表(基本上是一张表)

Name, Age, Grade
Bob, 24, 90.0
Jun, 20, 95.0

请记住,第一行是不能分割的标题(字符串)。你必须忽略它。再加上该行的索引为 0,除以 0 会破坏整个宇宙。将其更改为 enumerate(values[1:]) 以跳过第一行。

 elif choice == 2:
   for i, val in enumerate(values):
    a = sum(val[1] / i)
    print("The average age in the list is", a)
    b = sum(val[2] / i)
    print("The average grade in the list is", b)

然后你必须总结所有年级和所有年龄。一种方法是将其放入变量中。对于每一行(学生),它会将他的年龄添加到年龄总和中,并且对于他的成绩来说也是如此。然后我们可以通过将这些值除以列表中存在的学生人数来计算平均值。列表的大小为 -1,因为我们删除了第一行。len(values) 给出该列表中元素的数量。

 elif choice == 2:
     # EDIT: i forgot to set these var before calling +=, it would cause a NameError (undefined).
     sumAge = sumGrade = 0
     for i, val in enumerate(values[1:]):
        sumAge += val[1]
        sumGrade += val[2]
     averageAge = sumAge / (len(values)-1)         
     averageGrade = sumGrade / (len(values)-1)
     print("The average age in the list is", averageAge)
     print("The average grade in the list is", averageGrade)

做得更多

事实上,我会使用 object,因为您的列表只是按姓名、年龄和年级描述的学生列表。

class Student:
    """A class representing a student, described with a Name, Age and Grade"""
    def __init__(self, name :str, age :int, grade :float):
        self.name = name
        self.age = age
        self.grade = grade

所以你可以像以前一样设置你的学生列表

students: List[Student] = []

# There you can set your input. 
studentA = Student("Bob", 24, 95.0)
students.append(studentA)
studentB = Student("Jun", 20, 90.0)
students.append(studentB)

如果你想知道类是如何运作的。这是您的部分代码转换为类的示例。:

from typing import List

class Student:
    """A class representing a student, described with a Name, Age and Grade"""
    # __init__ is called when you create an object of type Student
    def __init__(self, name :str, age :int, grade :float):
        self.name = name
        self.age = age
        self.grade = grade
    
    # __str__ is  called in print(instanceofstudent), we can choose what to print, so we don't have to think about it when calling print(student)
    def __str__(self) -> str:
        return f"__str__ : {self.name} - {self.age} - {self.grade}"

    # __repr__ is called in print(listofstudent), same here, we choose what to display when we print a list of students.
    def __repr__(self) -> str:
        return f"__repr__ : {self.name} - {self.age} - {self.grade}"

students: List[Student] = [] # :List[Student] is just to give python more information about what we will put in the list. 

# There you can set your input. 
studentA = Student("Bob", 24, 95.0) # here we call __init__
students.append(studentA)
studentB = Student("Jun", 20, 90.0) # here we call __init__
students.append(studentB)

print(students) # here we call student.__repr__ to print all element of the list

sumAge = sumGrade = 0
for student in students:
    print(student) # here we call student.__str__
    print(student.name) # here we get the attributes directly

    sumAge += student.age
    sumGrade += student.grade

print(f"SumAge : {sumAge}")
print(f"SumAge : {sumGrade}")

averageAge = sumAge/len(students)
averageGrade = sumGrade/len(students)

print(f"average age of students : {averageAge}")
print(f"average grade of students : {averageGrade}")

推荐阅读