1

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]
kng
  • 11
  • 1
  • Does this answer your question? [Sorting list based on values from another list?](https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list) – pacukluka May 19 '20 at 11:49

2 Answers2

0

I think you can do this this with sorting:

sublist_ordered = sorted(sublist, key=lambda x: masterlist.index(x))
Paweł Kowalski
  • 524
  • 3
  • 9
0

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']
kng
  • 11
  • 1