我想用python打印一个二维矩阵。然而,我只能打印浮动的测试分数,而不能打印与行和列标题对应的字符串。
我想打印的是
studentName ex1 ex2 ex3 mike 78.0 89.0 89.0 Sarah 98.0 78.0 65.0 David 84.0 83.0 98.0
但是只得到了浮点数,却不知道如何添加行和列标题。
studentName = int(input("enter the number of student: "))
studentExam = int(input("how many exam scores: "))
names_students = []
# Initialize matrix
matrix = []
# For user input
for i in range(studentName): # A for loop for row entries
exam_student = []
names_students.append(input("enter name of students" + str(i+1) + ": "))
for j in range(studentExam): # A for loop for column entries
exam_student.append(float(input("enter exam " + str(j+1) + ": ")))
matrix.append(exam_student)
#for printing
for i in range(studentName):
for j in range(studentExam):
print(matrix [i][j], end=" ")
print()
需要在代码中做一点修改,虽然代码的复杂度不高,但效率很高。
studentName = int(input("enter the number of student: "))
studentExam = int(input("how many exam scores: "))
columns = ['name','s1','s2','s3']
# Initialize matrix
matrix = [columns]
# For user input
for i in range(studentName): # A for loop for row entries
exam_student = []
exam_student.append(input("enter name of students" + str(i+1) + ": "))
for j in range(studentExam): # A for loop for column entries
exam_student.append(float(input("enter exam " + str(j+1) + ": ")))
matrix.append(exam_student)
#for printing
for i in range(len(matrix)):
for j in range(len(matrix)):
print(matrix [i][j], end=" ")
print()