按给定的自定义顺序对列表进行排序

问题描述:

我有一个元组列表

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

我想按自定义顺序对每个元组的第一个元素("U"或"R")进行排序

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

顺序应为:

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

因此我示例的输出为:

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

如何在最佳时间内做到这一点? 谢谢

how can I do that in optimal time? Thanks

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

index()将返回适当的可比较键(元组的第一个元素)

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