You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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参数指定排序依据:
    1. 优先以rank字段值排序
    2. 当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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:05:17