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

如何在Python中按distanceToStar对数组中的多字典升序排序?

按指定字典键对数组排序的解决方案

给定数组需要按distanceToStar字段升序排序,这里提供两种Python实现方式:

原数组定义

planets = [
    {'name': 'Silopp', 'size': 14924, 'distanceToStar': 90248452, 'mass': 194532},
    {'name': 'Astrion', 'size': 152000, 'distanceToStar': 149302, 'mass': 2194},
    {'name': 'Valenus', 'size': 290450, 'distanceToStar': 20948593455, 'mass': 195293}
]

方法1:使用sorted()函数生成新数组

该方法返回排序后的新数组,原数组保持不变:

sorted_planets = sorted(planets, key=lambda x: x['distanceToStar'])

方法2:使用list.sort()原地排序

该方法直接修改原数组,不生成新数组:

planets.sort(key=lambda x: x['distanceToStar'])

排序后的结果按distanceToStar从小到大排列,顺序为:Astrion → Silopp → Valenus。

内容的提问来源于stack exchange,提问作者bocan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:50:37