-1
我有一个字典对象数组,我必须根据多个规则进行排序。基于多个键值和比较规则排序字典对象
这是样品类型的字典的样子:
dict1 = {'key1': '85', 'key2': '163', 'key3': '3'}
dict2 = {'key1': '3', 'key2': '23', 'key3': '1'}
dict3 = {'key1': '88', 'key2': '153', 'key3': '6'}
而且这些规则应遵循的顺序:
key1 - the higher value is the better
key2 - the higher value is the better
key3 - the lower value is the better
订货我的名单应该是这样的所以以后:
dict_list = [dict1, dict3, dict2]
#dict1 is the first obj, because it has the biggest key1 + key2 value and the 2. lowest key3 value
dict_list
物件按价值(预期结果):
# value name - high values (key1 + key2) - low values (key3)
1. dict1 248 3
2. dict3 241 6
3. dict2 26 1
从key1
和key2
我可以创建用于比较的绝对数量,但不幸的是,我不能这样做,因为key3
将仍然存在,我不能使用相同的逻辑吧。
所以我的问题:是否有可能为排序定义我自己的规则?有没有这样的任务的Python功能?
那么当你有{key1:2,key3:1}和{key1:1,key3:2}时你会怎么做? –
您可以使用键功能定义您自己的订购请参阅https://wiki.python.org/moin/HowTo/Sorting – pvg