EN VI

Python - How can i select one item of a object array by one object variable more efficiently?

2024-03-15 21:30:07
Python - How can i select one item of a object array by one object variable more efficiently?

I have a class "patient":

class patient:
    all_patients = []
    def __init__(self, pat_id):
        self.pat_id=pat_id
        self.plans=[]
        patient.all_patients.append(self)

I have to go through a log file with all therapy plans of all patients and I want to add each therapy plan to the correct patient.

My approach was this: (index is the current line of the log file)

if not any (x.pat_id == index[4] for x in patients):
    patients.append(patient(index[4]))
for pat in patient.all_patients:
    if (pat.pat_id == index[4]):
        if (index[11] not in pat.plans):
            total_plans+=1
            pat.plans.append(index[11])
print(len(patient.all_patients))
print(total_plans)

i think it return the right numbers, but i do not think that it is a very efficient way to do so. The log files are huge and all plans are several times (for each appointment once) in the log files.

Can you help me please to optimize this code?

Solution:

Taking the advise from another answer: enter link description here.

I would rewrite your code as follows:

class Patient:
    def __init__(self, pat_id: int):
        self.pat_id : int = pat_id
        self.plans: list = []

patients: dict = {}
total_plans: int = 0

patient_id, patient_plan = index[4], index[11]
if not patient_id in patients:
    patients.update({patient_id:Patient(patient_id)})
else:
    if patient_plan not in patients[patient_id].plans:
        total_plans += 1
        patients[patient_id].plans.append(patient_plan)
print(len(patients))
print(total_plans)

This would keep your patients in a dictionary using the hash table for quick look up and reference.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login