在字符串列表中查找完全匹配

Find exact match in list of strings

对此很陌生,请多多包涵...

我有一个预定义的单词列表

checklist = ['A','FOO']

line.split() 中的单词列表看起来像这样

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

我需要wordschecklist的精确匹配,所以我只找到'A':

if checklist[0] in words:

那没有用,所以我尝试了一些我在此处找到的建议:

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

无济于事,因为我显然无法查找这样的列表对象...对此有任何帮助吗?

这将为您提供完全匹配的列表。

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

与以下相同:

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

使用集合比遍历列表要快得多。

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

设置将满足您的需求。有一个 issubset 方法设置。示例如下:

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

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

如果只需要检测两个列表中是否有comment元素,可以换成intersection方法。

让我知道这是否适合你,

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

在 [68] 中:test.group(2)

输出[68]:'T'

在[69]中:test.group()

输出[69]: 'CAT'

在 [70] 中:test.group(1)

输出[70]:'C'

如果模式不匹配,则测试对象不存在。