Creating a report table in Python with nested lists

1k Views Asked by At

I need to create a table which would represent marks of students in various modules. I was thinking of doing the following representation:

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.

For example, I have:

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])

I am a little bit confused how to properly build a table so I could later count the average of rows, columns, marks and print student report. Is there a way to modify the algorithm so it would build a normal table?

1

There are 1 best solutions below

0
On BEST ANSWER

A "table" might not be the best tool for the job, but to get you started, let's make a list for the marks, and append to it where needed, making sure we start a new list for each student. Let's just initialise everything to -1 for now.

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]]

We now have a list of lists.

Notice a few things

  • I have added and extra student to show we have five lists of four modules.
  • The range does not include the last number so you don't need -1
  • marks=marks[i][j]=int didn't mean anything. I have just made a list and appended to it.

You can now change the scores of moduels, and find an average easily.

>>> 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

Now, there are alternatives such as a dictionary, which would allow you to look up students by name. Or even a defaultdict.