-1

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.

Jakob Lovern
  • 1,301
  • 7
  • 24
  • Your function creates and returns a new list, but your function usage throws it away. So which one is it? Create new list or modify existing list? – Kelly Bundy Apr 21 '23 at 23:54

1 Answers1

1

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)
yut23
  • 2,624
  • 10
  • 18