本文介绍了在python中按特定顺序对元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按自定义顺序对其进行排序?

How can I sort it by custom order?

输入:

[
    {value: "typeA"},
    {value: "typeC"},
    {value: "typeB"},
    {value: "typeC"},
    {value: "typeB"},
    {value: "typeA"}
]

预期结果:

[
    {value: "typeB"},
    {value: "typeB"},
    {value: "typeC"},
    {value: "typeC"},
    {value: "typeA"},
    {value: "typeA"}
]

my_own_order = ['typeB', 'typeC', 'typeA']

我的python代码如下:

My python code as following right now:

result = sorted(input, key=lambda v:v['value'])

推荐答案

>>> lst = [
...     {'value': "typeA"},
...     {'value': "typeC"},
...     {'value': "typeB"},
...     {'value': "typeC"},
...     {'value': "typeB"},
...     {'value': "typeA"}
... ]
>>> my_own_order = ['typeB', 'typeC', 'typeA']


typeBtypeCtypeA到0、1、2


Make a mapping between typeB, typeC, typeA to 0, 1, 2

>>> order = {key: i for i, key in enumerate(my_own_order)}
>>> order
{'typeA': 2, 'typeC': 1, 'typeB': 0}

并使用映射对键进行排序:

And use the mapping for sorting key:

>>> sorted(lst, key=lambda d: order[d['value']])
[{'value': 'typeB'},
 {'value': 'typeB'},
 {'value': 'typeC'},
 {'value': 'typeC'},
 {'value': 'typeA'},
 {'value': 'typeA'}]

这篇关于在python中按特定顺序对元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:15