[英]how to re-order a list based on another one that has the same items in python
I have two list with the same items in both of them.我有两个列表,其中包含相同的项目。 I want to sort the second
unordered
list based on the ordering of the first one.我想根据第一个
unordered
列表的顺序对第二个unordered
列表进行排序。
ordered_list = ["first_name", "last_name", "language", "gender", "country", ]
unordered_list = ["country", "gender", "first_name", "last_name", "language",]
unordered_list.sort(key=ordered_list)
print(unordered_list)
PS: I have a looooonger list to work with, this is just an example. PS:我有一个 looooonger 列表可以使用,这只是一个例子。
GOAL: the unordered_list
items need to be sorted exactly how items are ordered in ordered_list
目标:
unordered_list
项目需要按照ordered_list
项目的排序方式进行排序
Is there a better approach than the one above that doesn't work?有没有比上面那个不起作用的更好的方法?
Use the index as the key:使用索引作为键:
ordered_list = ["first_name", "last_name", "language", "gender", "country", ]
unordered_list = ["country", "gender", "first_name", "last_name", "language",]
unordered_list.sort(key= lambda x: ordered_list.index(x))
print(unordered_list)
Output输出
['first_name', 'last_name', 'language', 'gender', 'country']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.