如何将二维程序转换为一维?

时间:2015-04-03 01:45:50

标签: python while-loop

我的教授让我做一个二维程序来计算学生的平均成绩。现在他说他希望我把我的努力变成一个一维的程序,我不知道怎么做,有什么帮助吗?

import sys
    students = []
    grades = []

    while True:
        student = input ("Enter a name: ").replace(" ","")
        if  student.isalpha() == True and student != "0":
            while True:
                grade = input("Enter a grade: ").replace(" ","")
                if grade == "0" or grade == 0:
                    print ("\n")
                    print ("A zero is entered.")
                    sys.exit(0)
                if grade.isdigit()== True: 
                    grade = int(grade)
                    if grade >= 1 and grade <= 10:
                        if student in students:
                            index = students.index(student)
                            grades[index].append(grade)
                            break
                        else:
                            students.append(student)
                            grades.append([grade])
                            break
                    else:
                        print("Invalid grade.")
        elif student == "0": 
            print("A zero is entered.")
            break
        else:
            print ("Invalid name.")
    for i in range(0,len(students)): 
        print("NAME: ", students[i])
        print("GRADE: ", grades[i])
        print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")

例如,现在打印出来:

NAME:  Jack
GRADE:  [8, 7, 9]
AVERAGE:  8.0

但是我需要打印出来这样:

NAME:  Jack
GRADE:  8, 7, 9
AVERAGE:  8.0

1 个答案:

答案 0 :(得分:1)

我认为用grades.append([grade])替换grades.append(grade)会有所帮助。

好的,我想我现在更了解你的问题了。尝试这样打印:

print("GRADE: ", ", ".join(grades[i]))