Search code examples
pythonsortedlist

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.


Solution

  • 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']