Python – Customize the sorted list by pinning the first element

Customize the sorted list by pinning the first element… here is a solution to the problem.

Customize the sorted list by pinning the first element

I have a list

[25, 35, 54, 70, 68, 158, 78, 11, 18, 12]

I

want to sort this list by fixing the first element, i.e.: if I fix 35, the sorted list should look like this

[35, 54, 68, 70, 78, 158, 11, 12, 18, 25]

If I fix 158 as the first element, the sorted list should look like this

[158, 11, 12, 18, 25, 35, 54, 68, 70, 78]

Basically I want to fix the first element, the rest should be sorted order, if a number less than the first element is found, it should not be before the first element. Are there built-in functions in Python that can be used for this?

Solution

Just define a key function, such as:

Code:

def sorter(threshold):
    def key_func(item):
        if item >= threshold:
            return 0, item
        return 1, item

return key_func

This is achieved by returning a tuple so that numbers above the threshold are sorted below the threshold.

Test code:

data = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12]
print(sorted(data, key=sorter(70)))

Result:

[70, 78, 158, 11, 12, 18, 25, 35, 54, 68]

Related Problems and Solutions