[英]Sort list by a given custom order
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') 我想按每个元组的第一个元素('U'或'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()
将返回一个适当的可比较键(元组的第一个元素)
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.