自定义排序的Python列表

时间:2014-01-03 08:19:57

标签: python sorting

我有一个dicts列表:

ldicts = [{'name': '120-150'}, {'name': '90-120'}, {'name': '150-180'}, {'name': '>= 180'}, {'name': '<90'}, {'name': 'total'}]

我想按值升序对其进行排序,以便输出如下:

 sortedldicts = [{'name': 'total'}, {'name': '<90'}, {'name': '90-120'},{'name': '120-150'}, {'name': '150-180'}, {'name': '>= 180'}]

正常排序不起作用:

from operator import itemgetter
sortedldicts = sorted(ldicts , key=itemgetter('name'), reverse=True)

所以我假设我应该做一个自定义排序?任何提示或帮助将不胜感激。

1 个答案:

答案 0 :(得分:7)

使用re.findall提取数字:

>>> ldicts = [{'name': '120-150'}, {'name': '90-120'}, {'name': '150-180'}, {'name': '>= 180'}, {'name': '<90'}, {'name': 'total'}]
>>>
>>> import re
>>> sorted(ldicts, key=lambda d: map(int, re.findall(r'\d+', d['name'])))
[{'name': 'total'}, {'name': '<90'}, {'name': '90-120'}, {'name': '120-150'}, {'name': '150-180'}, {'name': '>= 180'}]
  • 如果您使用Python 3.x,请将map(int, ...)替换为list(map(int, ...))