简体   繁体   中英

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.

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:

['email1@email.com', 'email2@email.com', 'email3@email.com', 'email4@email.com']
['email4@email.com', 'email3@email.com', 'email2@email.com', 'email1@email.com']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM