在 Oracle SQL 中,有一个功能需要订购,如下所示:
order by decode("carrot" = 2
,"banana" = 1
,"apple" = 3)
在 python 中实现这一点的最佳方法是什么?
我希望能够通过它的键订购一个字典。而且该顺序不一定是按字母顺序或任何其他顺序 - 我确定顺序。
在 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)
您不能对 dict 本身进行排序,但可以将其转换为 (key, value) 元组的列表,并且可以对其进行排序。
您使用 .items() 方法来做到这一点。例如,
>>> {'a': 1, 'b': 2}
{'a': 1, 'b': 2}
>>> {'a': 1, 'b': 2}.items()
[('a', 1), ('b', 2)]
最有效的排序方法是使用键功能。使用 cmp 效率较低,因为必须为每对项目调用它,而使用 key 它只需要为每个项目调用一次。只需指定一个可调用对象,它将根据项目的排序方式对其进行转换:
sorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]])
上面定义了一个字典,它指定你想要的键的自定义顺序,并且 lambda 为旧字典中的每个键返回该值。
Python 的 dict 是一个 hashmap,所以它没有顺序。但是您可以单独对键进行排序,使用keys()方法从字典中提取它们。
sorted()
将比较函数和键函数作为参数。
你可以做你的解码的精确副本
sortedKeys = sorted(dictionary, {"carrot": 2
,"banana": 1
,"apple": 3}.get);
你不能对字典进行排序;字典是映射,映射没有顺序。
但是,您可以提取键并对它们进行排序:
keys = myDict.keys()
sorted_keys = sorted(keys, myCompare)
将会有OrderedDict
新的 Python 版本: http: //www.python.org/dev/peps/pep-0372/。
同时,您可以尝试其中一种替代实现:http : //code.activestate.com/recipes/496761/,Ordered Dictionary。
字典没有排序。您将需要保留密钥列表。
您可以将自己的比较函数传递给 list.sort() 或 sorted()。
如果您需要对多个键进行排序,只需将它们连接到一个元组中,然后对元组进行排序。