-4

我如何使用 name 属性对下面的 python 列表进行排序,

 [{'name':'Accra','url':''},
  {'name':'Dubai','url':''},
  {'name':'Birmingham','url':''},
  {'name':'Dhaka','url':''},
  {'name':'Abu Dhabi','url':''},
  {'name':'Lahore','url':''},
  {'name':'Karachi','url':''},
  {'name':'Kathmandu','url':''},
  {'name':'SEA','url':''}]
4

3 回答 3

5
In [26]: L = [{'name':'Accra','url':''},{'name':'Dubai','url':''},{'name':'Birmingham','url':''},{'name':'Dhaka','url':''},{'name':'Abu Dhabi','url':''},{'name':'Lahore','url':''},{'name':'Karachi','url':''},{'name':'Kathmandu','url':''},{'name':'SEA','url':''}]

In [27]: L.sort(key=lambda d:d['name'])

In [28]: L
Out[28]: 
[{'name': 'Abu Dhabi', 'url': ''},
 {'name': 'Accra', 'url': ''},
 {'name': 'Birmingham', 'url': ''},
 {'name': 'Dhaka', 'url': ''},
 {'name': 'Dubai', 'url': ''},
 {'name': 'Karachi', 'url': ''},
 {'name': 'Kathmandu', 'url': ''},
 {'name': 'Lahore', 'url': ''},
 {'name': 'SEA', 'url': ''}]
于 2013-10-30T06:59:56.847 回答
2
>>> from operator import itemgetter
>>> lis = [{'name':'Accra','url':''},{'name':'Dubai','url':''},{'name':'Birmingham','url':''},{'name':'Dhaka','url':''},{'name':'Abu Dhabi','url':''},{'name':'Lahore','url':''},{'name':'Karachi','url':''},{'name':'Kathmandu','url':''},{'name':'SEA','url':''}]
>>> sorted(lis, key=itemgetter('name'))
[{'url': '', 'name': 'Abu Dhabi'}, {'url': '', 'name': 'Accra'}, {'url': '', 'name': 'Birmingham'}, {'url': '', 'name': 'Dhaka'}, {'url': '', 'name': 'Dubai'}, {'url': '', 'name': 'Karachi'}, {'url': '', 'name': 'Kathmandu'}, {'url': '', 'name': 'Lahore'}, {'url': '', 'name': 'SEA'}]

要对列表进行就地排序,请使用:

lis.sort(key=itemgetter('name'))
于 2013-10-30T07:01:00.383 回答
0
pydoc sorted

得到 sorted 函数的用法

于 2013-10-30T07:02:37.747 回答