简体   繁体   English

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

[英]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 line.split()中的单词列表看起来像这样

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

I need the exact match of checklist in words , so I only find 'A': 我需要words checklist的完全匹配,所以我只找到'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. 有一个issubset方法。 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. 如果只需要测试两个列表中是否有注释元素,则可以更改为intersection方法。

Let me know if this works for you, 如果这对您有用,请告诉我

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

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

Out[68]: 'T' 出[68]:'T'

In [69]: test.group() 在[69]中:test.group()

Out[69]: 'CAT' 出[69]:'猫'

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

Out[70]: 'C' 出[70]:'C'

If the pattern in does not match, the test object does not exists. 如果模式in不匹配,则测试对象不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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