Python 在字符串列表中查找完全匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33644729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find exact match in list of strings
提问by origamisven
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':
我需要checklist
in的完全匹配words
,所以我只找到 '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?
无济于事,因为我显然无法寻找这样的列表对象......对此有帮助吗?
采纳答案by pushkin
This will get you a list of exact matches.
这将为您提供完全匹配的列表。
matches = [c for c in checklist if c in words]
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)
回答by binarysubstrate
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'}
回答by Xiaoqi Chu
Set will meet your needs. There is an issubset
method of set. The example is like following:
设置将满足您的需求。有一种issubset
设置方法。该示例如下所示:
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
方法。
回答by NHMPlus
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.
如果模式不匹配,则测试对象不存在。