gpt4 book ai didi

python - 使用 itemgetter 对字典列表进行排序

转载 作者:太空狗 更新时间:2023-10-30 01:22:46 25 4
gpt4 key购买 nike

这是我的词典:

a = [{"id":1,"data":{"age":16,"name":a}}, 
{"id":3,"data":{"age":35,"name":b}},
{"id":2,"data":{"age":9,"name":c}}]

我想按“年龄”字段排序。

对于 lambda 我使用:

sorted(a, key=lambda k: k['data']['age'])

如何使用 itemgetter 做到这一点?

最佳答案

你最好先给"a"、"b"和"c"加上引号,否则你会混淆dict a和char "a"

a = [{"id":1,"data":{"age":16,"name":"a"}}, 
{"id":3,"data":{"age":35,"name":"b"}},
{"id":2,"data":{"age":9,"name":"c"}}]

对于 itemgetter :

from operator import itemgetter

a = [{"id":1,"data":{"age":16,"name":"a"}},
{"id":3,"data":{"age":35,"name":"b"}},
{"id":2,"data":{"age":9,"name":"c"}}]

l=sorted(a, key = lambda k : itemgetter('age')(itemgetter('data')(k)) )

print (l)

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

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