gpt4 book ai didi

python - 在 python 中按特定顺序对元素进行排序

转载 作者:太空狗 更新时间:2023-10-29 20:34:41 25 4
gpt4 key购买 nike

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

输入:

[
{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'])

最佳答案

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

关于python - 在 python 中按特定顺序对元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34308635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com