KingJohnno
KingJohnno

Reputation: 602

Comparing two lists in Python (almost the same)

I have two lists with values in example:

List 1 = TK123,TK221,TK132 

AND

List 2 = TK123A,TK1124B,TK221L,TK132P

What I want to do is get another array with all of the values that match between List 1 and List 2 and then output the ones that Don't match.

For my purposes, "TK123" and "TK123A" are considered to match. So, from the lists above this, I would get only TK1124B.

I don't especially care about speed as I plan to run this program once and be done with it.

Upvotes: 1

Views: 196

Answers (3)

Chris Hagmann
Chris Hagmann

Reputation: 1096

This compares every item in the list to every item in the other list. This won't work if both have letters (e.g. TK132C and TK132P wouldn't match). If that is a problem, comment below.

list_1 = ['TK123','TK221','TK132'] 
list_2 = ['TK123A','TK1124B','TK221L','TK132P']

ans = []
for itm1 in list_1:
    for itm2 in list_2:
        if itm1 in itm2:
            break
        if itm2 in itm1:
            break
    else:
        ans.append(itm1)

for itm2 in list_2:
    for itm1 in list_1:
        if itm1 in itm2:
            break
        if itm2 in itm1:
            break
    else:
        ans.append(itm2)

print ans
>>> ['TK1124B']

Upvotes: 1

Jared
Jared

Reputation: 26397

>>> list1 = 'TK123','TK221','TK132'
>>> list2 = 'TK123A','TK1124B','TK221L','TK132P'
>>> def remove_trailing_letter(s):
...     return s[:-1] if s[-1].isalpha() else s
... 
>>> diff = set(map(remove_trailing_letter, list2)).difference(list1)
>>> diff
set(['TK1124'])

And you can add the last letter back in,

>>> add_last_letter_back = {remove_trailing_letter(ele):ele for ele in list2}
>>> diff = [add_last_letter_back[ele] for ele in diff]
>>> diff
['TK1124B']

Upvotes: 2

zeantsoi
zeantsoi

Reputation: 26193

For:

list_1 = ['TK123', 'TK221', 'TK132']
list_2 = ['TK123A', 'TK1124B', 'TK221L', 'TK132P']

Either of the two following snippets will yield a list of common items between two lists:

list(set(list_1).intersection(list_2))
# returns []

list(set(list_1) & set(list_2))
# returns []

To get a list of exclusive items:

list(set(list_1) ^ set(list_2)) 
# returns ['TK1124B', 'TK132P', 'TK123A', 'TK221', 'TK221L', 'TK132', 'TK123']

If you want to sort the resulting list, use the sorted method:

exclusive = list(set(list_1) ^ set(list_2)) 
sorted(exclusive)
# returns ['TK1124B', 'TK123', 'TK123A', 'TK132', 'TK132P', 'TK221', 'TK221L']

Upvotes: 1

Related Questions