简体   繁体   中英

Find exact match in list of strings

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?

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'}

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)

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.

Let me know if this works for you,

In [67]: test = re.match(r"(.*?)A(.*?)$", "CAT")

In [68]: test.group(2)

Out[68]: 'T'

In [69]: test.group()

Out[69]: 'CAT'

In [70]: test.group(1)

Out[70]: 'C'

If the pattern in does not match, the test object does not exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM