Bashar
Bashar

Reputation: 41

Matching two lists in python

I have two lists with different lengths.

list1=['T','P','M','M','A','R','k','M','G','C']
list2=['T','P','M','M','A','R','k','S','G','C','N']

By comparing list1 and list2: The results must be:

new_list1=['T','P','M','M','A','R','k','mis','M',  'G','C','mis']    
new_list2=['T','P','M','M','A','R','k','S',  'mis','G','C','N']      

The method is by matching the elements in two lists with duplicates. If there are a non-matching elements in the same position. For example in list1 there are three copies of M, in the list2 there are two copies. The results must refer to missing M from list2 in this position. The character S is missing from list1, results also must assign to missing.

Can anyone help me?

Upvotes: 4

Views: 163

Answers (2)

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

You can also try it. Its simple:

list1=['T','P','M','M','A','R','k','M','G','C']
list2 =['T','P','M','M','A','R','k','S','G','C','N']

if len(list1) > len(list2):
        diff = len(list1) - len(list2)
        for i in range(0, diff):
                list2.append('mis')
else:
        diff = len(list2) - len(list1)
        for i in range(0, diff):
                list1.append('mis')

new_list1 = []
new_list2 = []
for i in zip(list1,list2):
        if i[0] == i[1]:
                new_list1.append(i[0])
                new_list2.append(i[1])
        elif i[0] == 'mis' or i[1] == 'mis':
                new_list1.append(i[0])
                new_list2.append(i[1])
        else:
                new_list1.append(i[0])
                new_list2.append('mis')

                new_list1.append('mis')
                new_list2.append(i[1])

print new_list1
print new_list2

Output:

['T', 'P', 'M', 'M', 'A', 'R', 'k', 'M', 'mis', 'G', 'C', 'mis']
['T', 'P', 'M', 'M', 'A', 'R', 'k', 'mis', 'S', 'G', 'C', 'N']

Upvotes: 1

pacholik
pacholik

Reputation: 8972

Assuming "mis" is a special value:

from itertools import zip_longest

def create_matchs(alst, blst, mis="mis"):
    for a, b in zip_longest(alst, blst, fillvalue=mis):
        if a == b or mis in (a, b):
            yield a, b
        else:
            yield mis, b
            yield a, mis

list1 = ['T','P','M','M','A','R','k','M','G','C']
list2 = ['T','P','M','M','A','R','k','S','G','C','N']
new_list1, new_list2 = zip(*create_matchs(list1, list2))
print(new_list1)
print(new_list2)

Upvotes: 2

Related Questions