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
sorted(x, key=lambda x: order.index(x[0]))
index()
will return a proper comparable key (first element of tuple)
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]])
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