OneEyedOwl
OneEyedOwl

Reputation: 11

How can I sort this list in python

def project():
    JobList = []

    class Job:
        def __init__(self, name, cycle):
            self.name = name
            self.cycle = cycle
            JobList.append(self)

    #Acquire Job Info From User

    Job_A = float(input("What is the CPU cycle for Job A in ms? "))
    A = Job("A", Job_A)
    Job_B = float(input("What is the CPU cycle for Job B in ms? "))
    B = Job("B", Job_B)
    Job_C = float(input("What is the CPU cycle for Job C in ms? "))
    C = Job("C", Job_C)
    Job_D = float(input("What is the CPU cycle for Job D in ms? "))
    D = Job("D", Job_D)
    Job_E = float(input("What is the CPU cycle for Job E in ms? "))
    E = Job("E", Job_E)

    NewList = JobList.sort(key=lambda elem: elem[0])

    print(NewList)


project()

I know I can use

NewList = sorted(JobList,key = lambda x: x.cycle)

and it will sort my list from least to greatest, but I am looking another another way to do it. I have tried using a few other ways to sort my list from least to greatest but I havent gotten any of them to work.

Upvotes: 0

Views: 75

Answers (1)

Mark
Mark

Reputation: 92440

If you define __lt__() on your Job class in a way that defines what less than means between two instances, you can then just use .sort() or sorted(). This works because python only depends on < comparisons to sort.

class Job:
    def __init__(self, name, cycle):
        self.name = name
        self.cycle = cycle

    def __lt__(self, other):
        return self.cycle < other.cycle

    def __repr__(self):
        return f"Job({self.name}, {self.cycle})"

job_list = [
    Job("A", 1.5),
    Job("B", 6.5),
    Job("C", 0.3),
    Job("D", 2.9),
    Job("E", 1.8)
]

sorted(job_list)
# [Job(C, 0.3), Job(A, 1.5), Job(E, 1.8), Job(D, 2.9), Job(B, 6.5)]

FWIW, it is sometimes recommended to implement __eq__() with total_ordering as well to define all comparisons between objects. (Left if off for simplicity here since it wasn't needed)

Upvotes: 2

Related Questions