对对象列表进行自定义排序

2024-07-07 08:22:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张物品清单

actors = [Person('Raj' ,'Hindi'),
          Person('John',  'English'),
          Person('Michael' 'Marathi'),
          Person('Terry','Hindi'),
          Person('Terry', 'Telugu')]

我想根据他们的母语对这些人进行分类。依次是马拉地语、英语、印地语、泰卢固语。意味着我想按自定义逻辑对对象排序,而不是按升序或降序排序。你知道吗

我使用的是python3.7。你能帮我怎么做吗?你知道吗


Tags: english排序actors分类逻辑john物品person
2条回答

首先创建语言的优先级映射:

priority_map = {v: k for k, v in enumerate(('Marathi', 'English', 'Hindi', 'Telugu'))}

然后将sorted与自定义键一起使用:

res = sorted(actors, key=lambda x: priority_map[x.tongue])

或者,如果适用,将排序作为类的属性,如this example。你知道吗

你能做到的

sorted(actors, key = lambda x: mothertongue_list.index(x.tongue))

如果我们有,您可以通过tongue获得Person的母语,mothertongue_list是您想要的列表。你知道吗

相关问题 更多 >