在Oracle SQL中,有一个要按如下顺序排序的功能:
order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3)
在python中实现它的最佳方法是什么?
我希望能够通过它的键来命令一个字典.而且该顺序不一定按字母顺序或任何顺序 - 我确定顺序.
使用key
命名关键字参数sorted()
.
#set up the order you want the keys to appear here order = ["banana", "carrot", "apple"] # this uses the order list to sort the actual keys. sorted(keys, key=order.index)
为了获得更高的性能list.index
,您可以使用dict.get
.
#this builds a dictionary to lookup the desired ordering order = dict((key, idx) for idx, key in enumerate(["banana", "carrot", "apple"])) # this uses the order dict to sort the actual keys. sorted(keys, key=order.get)