gpt4 book ai didi

python - 对象列表的自定义排序

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:12 25 4
gpt4 key购买 nike

我有像

这样的对象列表
actors = [Person('Raj' ,'Hindi'),
Person('John', 'English'),
Person('Michael' 'Marathi'),
Person('Terry','Hindi'),
Person('Terry', 'Telugu')]

我想根据他们的母语对这份名单进行排序。依次为马拉地语、英语、印地语、泰卢固语。意味着我想按自定义逻辑而不是按升序或降序对对象进行排序。

我正在使用 python 3.7。你能帮我怎么做吗?

最佳答案

你可以做到

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

如果我们有,你可以通过 tongue 获取 Person 的母语,而 mothertongue_list 是一个按你想要的顺序排列的列表。

关于python - 对象列表的自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53883792/

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