在python中按特定顺序排序元素

时间:2015-12-16 09:47:14

标签: python list sorting dictionary

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

输入:

[
    {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代码现在如下:

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

4 个答案:

答案 0 :(得分:17)

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

typeBtypeCtypeA到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'}]

答案 1 :(得分:7)

试试这个:

sorted(input, key=lambda v: my_own_order.index(v['value']))

答案 2 :(得分:1)

接受输入并在my_order中设置顺序,它将按照该顺序打印

enter code here

user_input = input()
my_order = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1357902468'
print(*sorted(user_input, key=my_order.index),sep='')

答案 3 :(得分:0)

inp = input()
order = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468'
print(*sorted(inp, key=order.index), sep='')