使用嵌套列表在Python中创建报表

时间:2016-12-23 10:48:52

标签: python arrays nested-lists

我需要创建一个表格,代表各个模块中学生的标记。我正在考虑做以下表示:

Students, a list of strings that are student names. For each i such that
0 <=i <= len(Students) - 1, we refer to Students[i] as the i-th student.

Modules, a list of strings that are modules names. For each i such that
0 <=i <=len(Modules) - 1, we refer to Modules[i] as the i-th module.

Marks a table whose rows correspond to the students and columns     correspond to the modules. Marks[i][j] is an integer number defined as follows.
{ If Marks[i][j] = -1 this means that the i-th student is not registered
for the j-th module.
{ If Marks[i][j] =>0 then this is the mark of the i-th student for the
j-th module. We can assume that the marks are in range 0-100,
there is no need to check the validity of the data.

例如,我有:

students=['Artur', 'Igor', 'David', 'Andy']
modules=['DM', 'ISD', 'INS', 'IS']
marks=marks[i][j]=int
for i in range(0, len(students)-1) #i ranges over all row numbers
    for i in range(0, len(students)-1) #j ranges over all indices
      print(a[i][j])

我有点困惑如何正确构建一个表,以便我以后可以计算行,列,标记和打印学生报告的平均值。有没有办法修改算法,以便建立一个普通的表?

1 个答案:

答案 0 :(得分:0)

A&#34; table&#34;可能不是这项工作的最佳工具,但为了让你开始,让我们为这些标记制作一个清单,并在需要的地方附加,确保我们为每个学生开始一个新的清单。现在让我们将所有内容初始化为-1。

students=['Artur', 'Igor', 'David', 'Andy', 'Fran']
modules=['DM', 'ISD', 'INS', 'IS']
marks = []
for i in range(len(students)):
    marks.append([])
    for j in range(len(modules)):
      marks[i].append(-1)

>>> marks
[[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]

我们现在有一份清单清单。

注意一些事情

  • 我添加了额外的学生,以显示我们有五个四个列表 模块。
  • 该范围不包括您不需要的最后一个号码 -1
  • marks=marks[i][j]=int并不意味着什么。我刚刚做了 列表并附加到其中。

您现在可以更改模块的分数,并轻松找到平均值。

>>> marks[0][1] = 50
>>> marks
[[-1, 50, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1
, -1, -1]]
>>> for scores in marks:
...   print sum(scores)/len(scores)
...
11
-1
-1
-1
-1

现在,有一些替代品,如字典,可以让你按名字查找学生。甚至是默认用户。