微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何基于另一个在python中具有相同项目的列表重新排序

如何解决如何基于另一个在python中具有相同项目的列表重新排序

我有两个清单,两个清单中都有相同的项目。我想根据第一个列表的顺序对第二个unordered 列表进行排序。


ordered_list = ["first_name","last_name","language","gender","country",]

unordered_list = ["country","first_name",] 

unordered_list.sort(key=ordered_list)

print(unordered_list)

PS:我有一个比较宽松的清单,这只是一个例子。

目标:{unordered_list个项目需要准确排序,ordered_list中的项目排序方式

是否有比上述方法更好的方法

解决方法

使用索引作为键:

ordered_list = ["first_name","last_name","language","gender","country",]

unordered_list = ["country","first_name",] 

unordered_list.sort(key= lambda x: ordered_list.index(x))

print(unordered_list)

输出

['first_name','last_name','language','gender','country']

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。