gpt4 book ai didi

python - 如何使用 python 对对象列表进行排序?

转载 作者:行者123 更新时间:2023-11-28 19:40:22 24 4
gpt4 key购买 nike

我有一个如下所示的对象列表:

[{'id': 17L,
'price': 0,
'parent_count': 2},
{'id': 39L,
'price': 0,
'parent_count': 1},
{'id': 26L,
'price': 2.0,
'parent_count': 4},
{'id': 25L,
'price': 2.0,
'parent_count': 3}]

我想按 'parent_count' 对对象进行排序,以便看起来像这样:

 [{'id': 39L,
'price': 0,
'parent_count': 1},
{'id': 17L,
'price': 0,
'parent_count': 2},
{'id': 25L,
'price': 2.0,
'parent_count': 3},
{'id': 26L,
'price': 2.0,
'parent_count': 4}]

有人知道一个函数吗?

最佳答案

使用operator.itemgetter("parent_count")作为list.sort()key参数:

from operator import itemgetter
my_list.sort(key=itemgetter("parent_count"))

关于python - 如何使用 python 对对象列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11685834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com