Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sort a list by fixing 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

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

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

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

basically I want to fix the first element and the rest should be in sorted order, if there is a number that is lesser than the first element is found it should not go before first element. Is there a builtin function available for this in Python?

like image 380
Python_newbie Avatar asked Oct 27 '25 07:10

Python_newbie


1 Answers

Just define a key function like:

Code:

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

    return key_func

This works by returning a tuple such that the numbers above threshold will sort below the numbers under the threshold.

Test Code:

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

Results:

[70, 78, 158, 11, 12, 18, 25, 35, 54, 68]
like image 180
Stephen Rauch Avatar answered Oct 29 '25 21:10

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!