O
O
Oleg Petrov2017-09-11 11:58:44
Python
Oleg Petrov, 2017-09-11 11:58:44

How to make your own sorting in Python?

Good afternoon.
Already figured out how to sort elements in Python.
Now the next question has arisen. How do you set your own sort order?
For example, there is a row of elements "a1b2c"
Where a is the smallest and c is the largest.
How to convert the string "c2b1a" to the one in a1b2c?
That is, you need to sort the string y = sorted(list(x)) , but according to your own criteria.
How to make it?
For example, there are playing cards they have such an order of 23456789TJQKA in ascending order.
It is necessary that the program from the set "A926K" make the set "269KA" in ascending order.
I read that in Python there is a sort by key. That is, for any type of data, you can use the function to generate a key by which sorting will be performed. But how to do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-09-11
@Smeilz1

from functools import cmp_to_key

def my_sorter(a, b):
    if a > b:
        return -1
    elif a < b:
        return 1
    else:
        return 0

sorted(some_list, key=cmp_to_key(my_sorter))

You only need to define your sorting rules in the my_sorter function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question