Python Custom Key Sorter
Just as Java has the comparator and the comparable interface, Python allow the use of the built-in sort capability against complex input that needs a mapping function to determine the key against which a list of values has to be sorted.
Let’s take an example a list of bookings for a bus. On the first row, we have four seats number A1, B1, C1, and D1. The second row has the seats A2, B2, C2, and D2. If we have bookings for seats A11, C2, B2, D7, A3, C5 and we want the seats to be sorted in the order from the front to the back of the bus, we can use a function or lambda to tell sorted that it should first consider the numeric portion of the seat number and then the alphabet. The sort can be accomplished as follows:
booked_seat_nos = ['A11', 'C2', 'B2', 'D7', 'A3', 'C5']
booked_seat_nos.sort(key=lambda x: (x[1:]).zfill(3) + x[:1])
print(booked_seat_nos)
Both sorted()
and list.sort()
can be used in this manner.