Python semisort list of objects by attribute

65 Views Asked by At

I've got a list of an object:

class packet():
    def __init__(self, id, data):
        self.id, self.data = id, data

my_list = [packet(1,"blah"),packet(2,"blah"),packet(1,"blah"),packet(3,"blah"),packet(4,"blah")]

I want to extract all objects with a certain id (in the case of the above, I've made it 1) and paste them to the end. The solution I've come up with is:

def semisort(data, id):
    return [o for o in data if o.id != id] + [o for o in my_list if o.id = id]

semisort(my_list, 1)

It works and is relatively clear. I just feel like there's a way I could use sort to do this that would make it more pythonic.

1

There are 1 best solutions below

0
yut23 On

The standard sorting functions support a key argument, which takes a function that should return a value to sort by when called with an element. We can use the fact that False < True to implement your semisort straightforwardly:

def semisort(data, id):
    return sorted(data, key=lambda p: p.id == id)