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?
Just define a key function like:
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.
data = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12]
print(sorted(data, key=sorter(70)))
[70, 78, 158, 11, 12, 18, 25, 35, 54, 68]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With