Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list by a given custom order

Tags:

python

sorting

I have a list of tuples

x = [('U', 3), ('R', 3)]

I want to sort the list by a custom order for the first element of every tuple ('U', or 'R')

The order should be:

order = ["R", "D", "L", "U"]

so the output of my example would be:

x = [('R', 3), ('U', 3)]

how can I do that in optimal time? Thanks

like image 805
Dor Cohen Avatar asked Dec 11 '22 19:12

Dor Cohen


2 Answers

sorted(x, key=lambda x: order.index(x[0]))

index() will return a proper comparable key (first element of tuple)

like image 187
Ayush Avatar answered Dec 29 '22 18:12

Ayush


If the inputs are large, it's worth precalculating a dictionary for quick element position lookup:

order_map = {}
for pos, item in enumerate(order):
    order_map[item] = pos

sorted(x, key=lambda x: order_map[x[0]])
like image 23
Karoly Horvath Avatar answered Dec 29 '22 18:12

Karoly Horvath