Python-未知大小的2D列表

Python-未知大小的2D列表,python,python-3.x,Python,Python 3.x,我想创建一个2D列表来存储数据。n,我想在各种信息旁边存储一个自动递增的ID。所需的行数未知,但列数始终固定为6个数据值 我想要像下面这样的东西: [0, a, b, 1, 2, 3] [1, c, d, 4, 5, 6] [2, e, f, 7, 8, 9] 然后,我希望能够根据需要返回任何列,例如 [a, c, e] 目前,我正在尝试以下代码: student_array = [] student_count = 0 ... Student.student

我想创建一个2D列表来存储数据。n,我想在各种信息旁边存储一个自动递增的ID。所需的行数未知,但列数始终固定为6个数据值

我想要像下面这样的东西:

[0, a, b, 1, 2, 3]
[1, c, d, 4, 5, 6]
[2, e, f, 7, 8, 9]
然后,我希望能够根据需要返回任何列,例如

[a, c, e]
目前,我正在尝试以下代码:

    student_array = []
    student_count = 0
    ...
    Student.student_array.append(Student.student_count)
    Student.student_array.append(name)
    Student.student_array.append(course_name)
    Student.student_array.append(mark_one)
    Student.student_array.append(mark_two)
    Student.student_array.append(mark_three)
    Student.student_count = Student.student_count + 1

def list_students():
    print(Student.student_array[1])
我现在遇到的问题是,它显然是将新行追加到外部列表的末尾,而不是追加新行。i、 e:

[0, 'a', 'b', 1, 2, 3, 1, 'c', 'd', 4, 5, 6]
此外,当从每行中拉出第二列时,代码将沿着以下几行:

column_array = []
for row in Student.student_array:
    column_array.append(row[2])
print("Selected Data =", column_array)

现在的结构,所有数据都在一个列表中(顺便说一句,列表和数组在Python中的含义不同),实际上使获取列变得更容易。如果您的记录大小为
r_len=6
,并且希望
col=3
(第四列),则可以执行以下操作

>>> Student.student_array[col::r_len]
[1, 4, 7]
不过,要存储2D列表,您需要将每个学生的信息放入循环中的单独列表中:

current_student = [len(Student.student_array), name, course_name, mark1, mark2, mark3]
Student.student_array.append(current_student)
请注意,您不需要以这种方式维护单独的计数:外部列表的长度本身就说明了问题

要从如下2D数组中的
col=3
中获取数据,请使用理解:

>>> [s[col] for s in Student.student_array]
[1, 4, 7]
但是,将相关信息保存在未标记的格式中通常是一个糟糕的主意。您可以使用pandas之类的库添加标签,该库将为您维护适当的表,也可以将每个学生的信息封装到一个小班中。您可以编写自己的类,或使用类似于:

现在,您可以为每个学生提取
mark1
,而不是数字索引,数字索引可能会更改,并在以后导致维护问题:

>>> [s.mark1 for s in Student.student_array]
[1, 4, 7]

当你说“未知大小”时,你是指3个列表的未知大小还是未知数量的列表?如果你计划使用表格数据,你可能想看看这里的
pandas
。如果你想拥有一个数组数组,你应该首先将项附加到一个临时数组,然后将临时数组附加到student\u数组。如果您想要行和列索引,那是另一个问题。这并不太难,但您可能希望使用类似Pandas的内容。*列表列表,更具python风格。@mishsx如中所示,我不知道需要多少行。列的大小始终是固定的。
>>> [s.mark1 for s in Student.student_array]
[1, 4, 7]