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

时间:2013-10-30 06:58:30

标签: python

我如何使用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':''}]

3 个答案:

答案 0 :(得分: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': ''}]

答案 1 :(得分: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'))

答案 2 :(得分:0)

pydoc sorted

获取函数排序

的用法