[英]Change position of elements in a list so they cross match another list in Python
I have two lists with emails:我有两个包含电子邮件的列表:
masterlist = ['email1@email.com', 'email2@email.com', 'email3@email.com', 'email4@email.com']
sublist = ['email3@email.com', 'email4@email.com', 'email2@email.com', 'email1@email.com']
The masterlist is fixed but the order of the sublist should be changed so that the emails from the masterlist matches with the emails from the sublist and vice versa.主列表是固定的,但应更改子列表的顺序,以便主列表中的电子邮件与子列表中的电子邮件匹配,反之亦然。
For example, email1 in the masterlist is assigned to email3 in the sublist, therefore email1 in the sublist should also have the same position as email3 of the masterlist.例如,主列表中的 email1 分配给子列表中的 email3,因此子列表中的 email1 也应该与主列表中的 email3 具有相同的 position。
Desired sublist:所需的子列表:
sublist_ordered = ['email3@email.com', 'email4@email.com', 'email1@email.com', 'email2@email.com']
I'm thinking about using indexing to obtain a list of indices, but I couldn't figure out how to do the indexing.我正在考虑使用索引来获取索引列表,但我不知道如何进行索引。
order = [0, 1, 3, 2]
ordered_list = [sublist[i] for i in order]
I think you can do this this with sorting:我认为你可以通过排序来做到这一点:
sublist_ordered = sorted(sublist, key=lambda x: masterlist.index(x))
I think I found a solution:我想我找到了解决方案:
masterlist = ['email1@email.com', 'email2@email.com', 'email3@email.com', 'email4@email.com']
sublist = ['email3@email.com', 'email4@email.com', 'email2@email.com', 'email1@email.com']
order = []
for i in range(len(masterlist)):
mastermail = masterlist[i]
order.append(sublist.index(mastermail))
order.reverse()
sublist_ordered = [sublist[i] for i in order]
Output: Output:
['email1@email.com', 'email2@email.com', 'email3@email.com', 'email4@email.com']
['email4@email.com', 'email3@email.com', 'email2@email.com', 'email1@email.com']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.