首页 > 解决方案 > 复杂的字典排序

问题描述

我想对这样的列表进行排序:

# Basically alphabetic order with z in the second place.
order_list = ['a', 'z', 'b', 'c', ..., 'y'] 

# Original dict (I should have more than these but I stop at 'h' for demonstration)
d = {'a': [0, 1], 'b': [1, 0], 'd': [1, 1], 'e': [2, 3], 'g': [5, 0], 'h': [2, 0], ...}

''' 
sorting order:
1. sum(d.values()[1]): greater the better -> [3,1] > [1,2]
2. max(d.values()[1]): EACH ELEMENTS greater the better -> [2,2] > [3,1] ## notice that [4,2] would still be better than [9,1] since min([4,2]) > min([9,1])
3. order.index(d.values()[0]): follows the order_list
'''

# The result should be:
d = {'e': [2, 3], 'd': [1, 1], 'a': [0, 1], 'b': [1, 0], 'g': [5, 0], 'h': [2, 0]}

我的尝试是:

dict(sorted(d.items(), key=(
    lambda item: (sum(item[1]),
                  -min(item[1]),  # The problem occurs here*
                  order.index(item[0])))))

*由于它们是相同的项目[1],它会覆盖前一个!如何修复代码?

(ps.已编辑,是分钟)

标签: pythonlistsortingdictionary

解决方案


推荐阅读