Python中按rank及列表内元素层级排序字典的可行性咨询
字典排序实现方案
完全可以按照你指定的规则排序,不需要调整现有字典结构。
实现代码(Python)
# 待排序的字典列表 dict_list = [ {'rank': 6, 'other_ranks': [7, 5]}, {'rank': 1, 'other_ranks': [7, 11, 6, 2]}, {'rank': 0, 'other_ranks': [12]}, {'rank': 1, 'other_ranks': [13, 11, 4, 3]}, {'rank': 1, 'other_ranks': [14, 12, 6, 5]}, {'rank': 4, 'other_ranks': [5, 4, 3, 2]}, {'rank': 0, 'other_ranks': [12]} ] # 按照规则排序 sorted_list = sorted(dict_list, key=lambda d: (d['rank'], d['other_ranks'])) # 输出排序结果 for item in sorted_list: print(item)
排序逻辑说明
- 利用Python内置的
sorted()函数,通过key参数指定排序依据:- 优先以
rank字段值排序 - 当
rank相同时,直接比较other_ranks列表——Python列表的比较逻辑就是依次对比对应位置的元素,直到找到差异项或遍历完所有元素,正好匹配你的第三条规则。
- 优先以
排序后结果
{'rank': 0, 'other_ranks': [12]} {'rank': 0, 'other_ranks': [12]} {'rank': 1, 'other_ranks': [7, 11, 6, 2]} {'rank': 1, 'other_ranks': [13, 11, 4, 3]} {'rank': 1, 'other_ranks': [14, 12, 6, 5]} {'rank': 4, 'other_ranks': [5, 4, 3, 2]} {'rank': 6, 'other_ranks': [7, 5]}
内容的提问来源于stack exchange,提问作者pablos91
相关产品推荐
相关产品推荐

