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

如何按含重复值的列表对字典列表进行排序?

背景

在Python 3.9中,即使存在重复值,按第二个列表对大多数对象组成的列表进行排序也很简单:

>>> sorted(zip([5, 5, 3, 2, 1], ['z', 'y', 'x', 'w', 'x']))
[(1, 'x'), (2, 'w'), (3, 'x'), (5, 'y'), (5, 'z')]

若待排序列表包含字典,通常排序也能正常进行:

>>> sorted(zip([3, 2, 1], [{'z':1}, {'y':2}, {'x':3}])) 
[(1, {'x': 3}), (2, {'y': 2}), (3, {'z': 1})]

问题

但当用于排序的列表包含重复值时,会出现以下错误:

>>> sorted(zip([5, 5, 3, 2, 1], [{'z':1}, {'y':2}, {'x':3}, {'w': 4}, {'u': 5}])) 
*** TypeError: '<' not supported between instances of 'dict' and 'dict'

这个问题让人困惑:待排序列表的值为何会影响用于排序的列表?

替代解决方案

一种不够优雅的方案是通过索引从列表中获取字典对象:

>>> sort_list = [5, 5, 3, 2, 1]    
>>> dicts_list = [{'z':1}, {'y':2}, {'x':3}, {'w': 4}, {'u': 5}]
>>> [dicts_list[i] for _, i in sorted(zip(sort_list, range(len(sort_list))))]
 [{'u': 5}, {'w': 4}, {'x': 3}, {'z': 1}, {'y': 2}]

相关问题

StackOverflow上已有许多类似问题,涉及:

  • 按字典值对字典列表排序
  • 按ID对字典列表排序
  • 字典排序时的顺序问题
    但这种包含重复值的特定情况尚未被讨论过。

内容的提问来源于stack exchange,提问作者M.G.Poirot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:05:27