Find exact match in list of strings

37,628

Solution 1

This will get you a list of exact matches.

matches = [c for c in checklist if c in words]

Which is the same as:

matches = []
for c in checklist:
  if c in words:
    matches.append(c)

Solution 2

Using a set would be much faster than iterating through the lists.

checklist = ['A', 'FOO']
words = ['fAr', 'near', 'A']
matches = set(checklist).intersection(set(words))
print(matches)  # {'A'}

Solution 3

Set will meet your needs. There is an issubset method of set. The example is like following:

checklist = ['A','FOO']
words = ['fAr', 'near', 'A']

print set(checklist).issubset(set(words))

If you only need test if there is comment element in two list, you could change to intersection method.

Share:
37,628
origamisven
Author by

origamisven

Updated on July 20, 2022

Comments

  • origamisven
    origamisven almost 2 years

    very new to this so bear with me please...

    I got a predefined list of words

    checklist = ['A','FOO']
    

    and a words list from line.split() that looks something like this

    words = ['fAr', 'near', 'A']
    

    I need the exact match of checklist in words, so I only find 'A':

    if checklist[0] in words:
    

    That didn't work, so I tried some suggestions I found here:

    if re.search(r'\b'checklist[0]'\b', line): 
    

    To no avail, cause I apparently can't look for list objects like that... Any help on this?

  • CodeMonkey
    CodeMonkey about 8 years
    The set methods are really golden, if you have large data sets they are much much quicker than using for loops.
  • user1261558
    user1261558 over 7 years
    This method did not work. I gain "False" when I should get "True".