Reset sorting criteria

Asked 2 years ago, Updated 2 years ago, 72 views

In general, it is sorted with the standard 0<1<2<3<4<5<6<7<8<9
I would like to arrange it based on 1<2<3<4<5<6<7<8<9<0.
I remember doing it in C++ as a way to completely redefine the vs. comparison operator Is there a similar function in Python, or is there any other easy way to change the sorting criteria?

python sorting

2022-09-22 18:41

1 Answers

You can create a custom comparison function and compare it.

import random
import functools

def _compare(x, y):
    if   x == 0: return 1
    elif y == 0: return -1
    elif x < y:  return -1
    else:        return 0

L = list(range(10))
random.shuffle(L)
print(f'target: {L}')
print('sorted: {}'.format(sorted(L, key=functools.cmp_to_key(_compare))))

target: [3, 6, 0, 4, 9, 8, 5, 1, 2, 7]
sorted: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]


2022-09-22 18:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.