5

这是我的字典:

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

4

2 回答 2

3

最好先在 "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)
于 2013-10-09T16:49:45.937 回答
0

你可以这样使用它:

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}]
于 2013-10-09T16:54:37.660 回答