Python将当前列表转换为2d

时间:2015-03-22 02:49:01

标签: python list

我设计了一个按照我希望的方式运作的代码,向我私立学校的管理员询问学生人数,每个学生输入的等级数,最后是他们所选课程的课程代码。

COLS= int(input("number of students to enter: "))
ROWS= int(input("number of grades per student: "))


def main(COLS,ROWS):
    number =[]


    for c in range(COLS):
        student =(input("enter student Name: "))
        number.append(student)

        for r in range (ROWS):
            course=input("Enter course Code: ")
            number.append(course)
            grades =(input("Enter grade for module: "))
            number.append(grades)

    print(number)

main(COLS,ROWS)

输出的一个例子是:

number of students to enter: 3
number of grades per student: 2
enter student Name: LarryH
Enter course Code: Math202
Enter grade for module: 80
Enter course Code: Sci101
Enter grade for module: 90
enter student Name: JeromeK
Enter course Code: TT101
Enter grade for module: 60
Enter course Code: PSY205
Enter grade for module: 50
enter student Name: CheungL
Enter course Code: PS100
Enter grade for module: 80
Enter course Code: Math300
Enter grade for module: 50
['LarryH', 'Math202', '80', 'Sci101', '90', 'JeromeK', 'TT101', '60', 'PSY205', '50', 'CheungL', 'PS100', '80', 'Math300', '50']

现在代码可以正常工作,除了输出的最后一行,列表是与学生及其各自的成绩和课程代码一起提供的。

我正在尝试而不是我的输出产生那个1d列表,产生一个2d列表,例如:

[
   ["Andre", "MA22", 79, "MA300", 88, "CM202", 69],
   ["Larry", "PS44", 67, "MA555", 80, "ACC200", 67], 
   ...
  ]

有没有人对我在代码中可能改变的内容有任何建议,以产生如上所述的所需输出,

谢谢

1 个答案:

答案 0 :(得分:0)

在第一个循环中,您可以创建一个新的临时数组来存储该特定学生的数据,例如:

for c in range(COLS):
    studentInfo = [] # Info per-student
    student =(input("enter student Name: "))
    studentInfo.append(student)

    for r in range (ROWS):
        course=input("Enter course Code: ")
        studentInfo.append(course)
        # ...
        # ...

    number.append(studentInfo)

您还可以考虑将学生信息存储在词典中,而不是列表中,以便订单不那么重要。所以而不是:

singleStudentInfo = ["Andre", "MA22", 79, "MA300", 88, "CM202", 69]

你会:

singleStudentInfo = {"name": "Andre", "MA22": 79, "MA300": 88, "CM202": 69}