Question

I'm making a program that lists students, their degree and courses, among other things, for browsing. I haven't been able to wrap my head around what would be the way to iterate through an item of a specific index in a list of lists. The list of lists contains student information like this:

[['2004S','3001','Johnson John','149','HETY2','STIL'],
['2004S','3002','Steveson Steve','224','HETY2','SEIT'],
['2004S','3003','Jackson Jack','270','HETY2','SEIT'],
...
['2007S','3124','Ericsson Eric','286','HETY2','SPII']]

What I want to do is evaluate the first item of each list with an input I get from an Entry widget. The first item is the year a student has started their studies. So in the Entry field I ask what year's students the user wants to browse. If the value evaluates true, I append the whole list into another list, all of which I display on the screen later. Something like this:

class Model():
...
    def searched_year(self, year):
        for object in self.student.parse_student_info():
            for elem in range(len(self.student.parse_student_info())):
                matching = [object for elem in object if str(year) in elem]
        return matching

The parse_student_info() method is called from the Student class with the 'student' object and it returns the whole list of lists, as seen above. The argument 'year' is the StringVar I get from the Entry widget. This code returns an empty list each time (and does not yet limit the search to an index). What is the best way of doing this?

EDIT:

More essential code:

class Student():
...
    def parse_student_info(self):
        with open('opiskelijat.txt', 'r') as src:
            separ = src.readlines()
            studentinfo = [elem.strip().split(';') for elem in separ]
            return studentinfo

This is the parse_student_info() method in the Student class. It returns the list of lists you see above. It works as intended. Below is the search_year() method that calls the method in question.

UIController():
...
    def search_year(self, year):
        mode = Model()
        return mode.searched_year(year)

The UIController class controls all the different Frame classes that contain the buttons and other widgets, and it also interacts with the Model class that handles the information from Student, Course and Degree classes.

So far the method still prints an empty list.

Was it helpful?

Solution

The goal is to take the output of parse_student_info() and return a list of lists where the first element of each sub-list matches a given value, yes? Try this:

def searched_year(self, year):
    return [rec for rec in self.student.parse_student_info() if rec[0] is year]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top