Categories
Mastering Development

Python: Removing the first element of a list in a For Loop

This is the picture of the csv file
Link to the csv file

Context: I am reading in a csv file of students’ marks on different subjects with the students’ name on the first column and their gender on the second, with the the subject on the row.

def openfile(csvfile):
with open(csvfile,'r') as file:
    lines = file.readlines()[1:]
return lines

In this code, I am trying to invert the rows and the columns as I’m trying to get the lists of each subjects’ grades instead of the students’.

def convert(lines):
    x = [] # List of subject grades
    lst = [] # List of each list of subject grades
    for line in lines:
        data = line.split(',')[2:]
        x.append(float(data[0]))
        lst.append(x)
        data = data[1:] # My attempt to only refer to each of the grade of the next subject
    print(lst)

With the print of lst list, I seem to only get multiple duplications of x list (same amount as the number of subjects there are in the file) instead of each of the subjects’ list of grades. In this For loop, how do I remove or slice the previous element of data and only refer to the next?

Note: I’ve intentionally indexed the data to remove the subject name row and the student and gender columns.

Expected output: [[55.0, 75.0, 25.0, 78.0, 58.0, 0.0, 65.0, 38.0, 10.0, 95.0, 47.0, 11.0, 55.0, 67.0, 95.0, 96.0, 7.0, 7.0, 63.0, 31.0, 75.0, 98.0, 65.0, 6.0, 79.0, 92.0, 22.0, 16.0, 44.0, 18.0], [List 2], [List 3] and so on]

Leave a Reply

Your email address will not be published. Required fields are marked *