Python 在一起添加数组时,只能将列表(而不是“int”集中到列表
我有一个项目,我必须把一个学生的考试分数加到班级总数中,然后找出班级平均分Python 在一起添加数组时,只能将列表(而不是“int”集中到列表,python,integer,Python,Integer,我有一个项目,我必须把一个学生的考试分数加到班级总数中,然后找出班级平均分 AllStudents = [] Sum = 0 ClassSum = [] Total = [] for x in range(2): name = input("enter student name: ") Student = [] Student.append(name) StudentPoint1 = int(input("points for t
AllStudents = []
Sum = 0
ClassSum = []
Total = []
for x in range(2):
name = input("enter student name: ")
Student = []
Student.append(name)
StudentPoint1 = int(input("points for test 1: "))
if StudentPoint1 > 20:
print("Test 1 score invalid, should be less than 20")
StudentPoint2 = int(input("points for test 2: "))
if StudentPoint2 > 25:
print("Test 2 score invalid, should be less than 25")
StudentPoint3 = int(input("points for test 3: "))
if StudentPoint1 > 35:
print("Test 3 score invalid, should be less than 35")
Student.append(StudentPoint1)
Student.append(StudentPoint2)
Student.append(StudentPoint3)
Sum = StudentPoint1 + StudentPoint2 + StudentPoint3
Total.append(Sum)
ClassSum.append(Total + Sum)
AllStudents.append(Student)
print(ClassSum)
print(AllStudents)```
在显示ClassSum.append(Total+Sum)的行中,我得到一个错误“只能将列表(而不是“int”)集中到列表”试试看
ClassSum.append(sum(Total))
不能将整数和列表作为操作数执行加法。另外,当
Total
已将Sum
作为其元素时,为什么要尝试将Sum
添加到Total
。您正在尝试将列表和整数变量相加。如果您尝试为每个学生添加Sum,则需要使用列表索引进行访问。
ClassSum.append(Total[x]+Sum)
我不知道您到底想做什么,但我认为用“+=”递增比追加到列表中要好。如果有帮助,我编写了以下代码:
AllStudents = []
Sum = 0
ClassSum = 0
Total = []
for x in range(2):
name = input("enter student name: ")
Student = []
Student.append(name)
StudentPoint1 = int(input("points for test 1: "))
if StudentPoint1 > 20:
print("Test 1 score invalid, should be less than 20")
StudentPoint2 = int(input("points for test 2: "))
if StudentPoint2 > 25:
print("Test 2 score invalid, should be less than 25")
StudentPoint3 = int(input("points for test 3: "))
if StudentPoint1 > 35:
print("Test 3 score invalid, should be less than 35")
Student.append(StudentPoint1)
Student.append(StudentPoint2)
Student.append(StudentPoint3)
Sum = StudentPoint1 + StudentPoint2 + StudentPoint3
ClassSum+=Sum
AllStudents.append(name)
print(ClassSum)
print(AllStudents)
print(f'Average is {ClassSum/len(AllStudents)}')
Total和ClassSum代表什么?
Total
是一个列表,而Sum
是int。这里的问题是,Total
是一个列表,您不能向列表中添加数字(就像您不能回答“What is 4+table?”问题一样),它们是两种不同类型的信息,不能一起添加。既然Total
是每个学生的Sum
的列表,你介意解释一下ClassSum
到底代表什么吗?