Skip to content
Advertisement

Python custom function for sorting a list of objects

A list of Point class objects is given. The Point class is as follows:

class Point:
    def __init__(self, value, segment, is_start=False):
        self.value = value
        self.is_start = is_start

The goal is to sort the list by the value attribute provided that if two objects have the same value attributes, the object whose is_start value is True should go before the object whose is_start value is False.

An example of input:

[Point(3, False), Point(3, True), Point(1, True),]

I’ve tried using array.sort(key=lambda x: x.value) and the output was:

[Point(1, True), Point(3, False), Point(3, True),]

But it doesn’t satisfy the condition stated before (Point(3, True) should be before Point(3, False)).

An example of desired output:

[Point(1, True), Point(3, True), Point(3, False),]

What function to use to satisfy the stated condition?

Advertisement

Answer

Try this.

sorted(x, key=lambda x: (x.value, not x.is_start))

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement