使用Python中的自定义顺序对列表进行排序 [英] Sort a list with a custom order in Python

查看:80
本文介绍了使用Python中的自定义顺序对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

mylist = [['123', 'BOOL', '234'], ['345', 'INT', '456'], ['567', 'DINT', '678']]

我想按1的顺序对其进行排序.DINT 2. INT 3. BOOL

I want to sort it with the order of 1. DINT 2. INT 3. BOOL

结果:

[['567', 'DINT', '678'], ['345', 'INT', '456'], ['123', 'BOOL', '234']]

我在stackoverflow中看到了其他类似的问题,但没有类似的问题或对我很容易适用.

I've seen other similar questions in stackoverflow but nothing similar or easily applicable to me.

推荐答案

SORT_ORDER = {"DINT": 0, "INT": 1, "BOOL": 2}

mylist.sort(key=lambda val: SORT_ORDER[val[1]])

我们在这里所做的全部工作是通过为列表中的每个元素而不是整个列表返回一个整数来提供一个新的元素进行排序.我们可以使用内联三元表达式,但这会有点笨拙.

All we are doing here is providing a new element to sort on by returning an integer for each element in the list rather than the whole list. We could use inline ternary expressions, but that would get a bit unwieldy.

这篇关于使用Python中的自定义顺序对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆