我有一个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)
所以我假设我应该做一个自定义排序?任何提示或帮助将不胜感激。
答案 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'}]
map(int, ...)
替换为list(map(int, ...))
。