我需要一个二维列表来存储有关学生及其成绩的信息。
当我运行我的程序时,我只得到一个数字列表,但我需要为每个学生提供不同的列表。
这是我到目前为止所做的:
COLS= int(input("number of students to enter "))
ROWS= int(input("number of grades per student "))
def main():
number =[]
for c in range(COLS):
grades = []
student =(input("enter student ID number "))
number.append(student)
number.append(grades)
for r in range (ROWS):
grade =(input("Enter grade for module: "))
grades.append(grade)
print(number)
当我运行该程序时,它表示有一个缩进的块并突出显示"等级" 我做错了什么?
答案 0 :(得分:1)
具有正确缩进的代码:
COLS= int(input("number of students to enter "))
ROWS= int(input("number of grades per student "))
def main():
number =[]
for c in range(COLS):
grades = []
student =(input("enter student ID number "))
number.append(student)
number.append(grades)
for r in range (ROWS):
grade =(input("Enter grade for module: "))
grades.append(grade)
print(number)
main()
现在执行。
这是替代版本,更好的IMO:
from collections import OrderedDict
COLS= int(input("number of students to enter: "))
ROWS= int(input("number of grades per student: "))
def main():
student_grades = OrderedDict()
for c in range(COLS):
student =(input("enter student ID number: "))
student_grades[student] = []
for r in range(ROWS):
grade =(input("Enter grade for module: "))
student_grades[student].append(grade)
print(student_grades)
# exaple output OrderedDict([('123', ['2', '3']), ('412', ['4', '5'])])
main()
答案 1 :(得分:1)
你可能想要的是一个列表,其中包含第一个位置的学生ID和后续位置的成绩:
students= int(input("number of students to enter: "))
grades= int(input("number of grades per student: ")) + 1
class = []
for i in range(students):
for j in range(grades):
if j == 0:
m = input("Please input Student ID: ")
class.append(m)
elif:
m = input("Please input %j th grade: ")
class.append(m)
答案 2 :(得分:0)
二维列表如下所示:
two_dim = [[0,1,1,1,1,1],
[1,0,1,0,0,0],
[1,1,0,1,1,0]]
因此,每个行都是不同的列表,它们组合在另一个列表中。要调用元素,只需输入
即可two_dim[row_number][column_number]
这是Google搜索者的一般答案,现在针对您的问题,您需要将输入括在括号中以将行作为列表传递,而不是以单维列表结束。我会用这样的东西代替:
student_count= int(input("number of students to enter "))
grade_count = int(input("number of grades per student "))
grades = []
for i in range(student_count):
print("The next student")
grades.append([int(input("The next student grade")) for j in range(grade_count)])
print(grades)
答案 3 :(得分:0)
Matrix = [5][5]
Matrix = [[0 for x in range(5)] for x in range(5)]
您现在可以将项目添加到列表中:
Matrix[0][0] = 1
Matrix[4][0] = 5
print Matrix[0][0] # prints 1
print Matrix[4][0] # prints 5