I have a class called Student, where they have two attributes: studentName and a unique number for each student, studentID.
In another class, called Course, I already have a function
add_student(self, student)
that adds the given student to the given course. I want to create another function add_student_list(self, lst)
which intakes a list of studentIDs. I have a for loop which looks at the IDs in lst to see which students to add, I just need to call the add_student(self, student)
function for the ones in lst, however, I'm unable to do this, as I only have an id, and not the student object.
So my question is, how can I call the necessary student object based on the unique ID?
EDIT: here's the relevant part for my code:
import itertools
import pandas as pd
class Student (object):
#The following two objects are used to assign them unique IDs and to keep track of them.
id_iter = itertools.count()
all_students = pd.DataFrame(columns=["Student", "Student ID"])
#Adding a new student:
def __init__(self, studentName):
#The name of the student will be given, the ID will be generated:
self.studentName = [studentName, next(self.id_iter)]
#The new student will have a list of courses attended:
self.courses = pd.DataFrame(columns=["Course", "Course ID", "Passed/Failed", "Completed Assignments"])
#The new student will be added to the list of all students:
Student.all_students = pd.concat([Student.all_students, pd.DataFrame.from_dict({"Student": self.studentName[0], "Student ID": self.studentName[1]}, orient = "index")], ignore_index = True, axis = 1)
Student.all_students = Student.all_students.dropna(axis=1)
def __str__(self):
return str(self.studentName)
class Course (object):
#The two objects are similar to that of the student class:
id_iter = itertools.count()
all_courses = pd.DataFrame(columns=["Course", "Course ID"])
#the courses are similarly added as students above
def add_student(self,student,completed_assignments):
#this adds students with the number of assingments they completed (not relevant), the code is not relevant
def add_student_list(self, lst):
for i in range(0,len(lst)):
for j in range(0,len(Student.all_students.swapaxes("index", "columns"))):
if lst[i][0] == Student.all_students[j][1]:
self.add_student()
CodePudding user response:
Two methods:
Store your students in a dictionary with a id as the key. Than can retrieve the students based on their ids.
Search through the students everytime you have a list.
ids_to_search = [2, 34, 3]
students = [student for student in students if student.id==id_to_search]