>>> lst = [ ... {'value': "typeA"}, ... {'value': "typeC"}, ... {'value': "typeB"}, ... {'value': "typeC"}, ... {'value': "typeB"}, ... {'value': "typeA"} ... ] >>> my_own_order = ['typeB', 'typeC', 'typeA']
使之间的映射typeB
,typeC
,typeA
0,1,2
>>> order = {key: i for i, key in enumerate(my_own_order)} >>> order {'typeA': 2, 'typeC': 1, 'typeB': 0}
并使用映射进行排序键:
>>> sorted(lst, key=lambda d: order[d['value']]) [{'value': 'typeB'}, {'value': 'typeB'}, {'value': 'typeC'}, {'value': 'typeC'}, {'value': 'typeA'}, {'value': 'typeA'}]
试试这个:
sorted(input, key=lambda v: my_own_order.index(v['value']))