按给定的自定义顺序对列表进行排序 [英] Sort list by a given custom order
本文介绍了按给定的自定义顺序对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个元组列表
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)
这篇关于按给定的自定义顺序对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文