自定义排序的Python列表

我有一个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)

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

最佳答案 使用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,…)).

点赞