use*_*986 3 python sql-order-by
在Oracle SQL中,有一个要按如下顺序排序的功能:
order by decode("carrot" = 2
,"banana" = 1
,"apple" = 3)
Run Code Online (Sandbox Code Playgroud)
在python中实现它的最佳方法是什么?
我希望能够通过它的键来命令一个字典.而且该顺序不一定按字母顺序或任何顺序 - 我确定顺序.
rec*_*ive 15
使用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)
Run Code Online (Sandbox Code Playgroud)
为了获得更高的性能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)
Run Code Online (Sandbox Code Playgroud)
您本身无法订购字典,但可以将其转换为(键,值)元组列表,然后可以对其进行排序。
您可以使用 .items() 方法来执行此操作。例如,
>>> {'a': 1, 'b': 2}
{'a': 1, 'b': 2}
>>> {'a': 1, 'b': 2}.items()
[('a', 1), ('b', 2)]
Run Code Online (Sandbox Code Playgroud)
最有效的排序方法是使用键函数。使用 cmp 效率较低,因为必须为每对项目调用它,而使用 key 只需为每个项目调用一次。只需指定一个可调用函数,该可调用函数将根据项目的排序方式对其进行转换:
sorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]])
Run Code Online (Sandbox Code Playgroud)
上面定义了一个字典,指定所需键的自定义顺序,并且 lambda 为旧字典中的每个键返回该值。
| 归档时间: |
|
| 查看次数: |
4484 次 |
| 最近记录: |