这是我的字典:
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 = [{"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)
你可以这样使用它:
sorted(a, key = lambda k : itemgetter('age')(itemgetter('data')(k)) )
输出:
[{'data': {'age': 9, 'name': 'c'}, 'id': 2},
{'data': {'age': 16, 'name': 'a'}, 'id': 1},
{'data': {'age': 35, 'name': 'b'}, 'id': 3}]