我有两个列表 - query
和line
。我的代码找到query
,例如:
["president" ,"publicly"]
包含在line
(订单事项)中,例如:
["president" ,"publicly", "told"]
这是我目前正在使用的代码:
if ' '.join(query) in ' '.join(line)
问题是,我只想匹配整个单词。因此,下面的查询不会传递条件语句:
["president" ,"pub"]
我该怎么做?
答案 0 :(得分:1)
您可以使用正则表达式和\b
字边界:
import re
the_regex = re.compile(r'\b' + r'\b'.join(map(re.escape, ['president', 'pub'])) + r'\b')
if the_regex.search(' '.join(line)):
print 'matching'
else:
print 'not matching'
作为替代方案,您可以编写一个函数来检查给定列表是否是该行的子列表。类似的东西:
def find_sublist(sub, lst):
if not sub:
return 0
cur_index = 0
while cur_index < len(lst):
try:
cur_index = lst.index(sub[0], cur_index)
except ValueError:
break
if lst[cur_index:cur_index + len(sub)] == sub:
break
lst = lst[cur_index + 1:]
return cur_index
您可以将其用作:
if find_sublist(query, line) >= 0:
print 'matching'
else:
print 'not matching'
答案 1 :(得分:1)
只需使用“in”运算符:
mylist = ['foo', 'bar', 'baz']
'foo' in mylist
- &gt;返回True
'bar' in mylist
- &gt;返回True
'fo' in mylist
- &gt;返回False
'ba' in mylist
- &gt;返回False
答案 2 :(得分:1)
这是一种方式:
re.search(r'\b' + re.escape(' '.join(query)) + r'\b', ' '.join(line)) is not None
答案 3 :(得分:1)
只是为了好玩,你也可以这样做:
a = ["president" ,"publicly", "told"]
b = ["president" ,"publicly"]
c = ["president" ,"pub"]
d = ["publicly", "president"]
e = ["publicly", "told"]
from itertools import izip
not [l for l,n in izip(a, b) if l != n] ## True
not [l for l,n in izip(a, c) if l != n] ## False
not [l for l,n in izip(a, d) if l != n] ## False
## to support query in the middle of the line:
try:
query_list = a[a.index(e[0]):]
not [l for l,n in izip(query_list, e) if l != n] ## True
expect ValueError:
pass
答案 4 :(得分:0)
您可以使用issubset方法来实现此目的。只需:
a = ["president" ,"publicly"]
b = ["president" ,"publicly", "told"]
if set(a).issubset(b):
#bla bla
这将返回两个列表中的匹配项。
答案 5 :(得分:0)
您可以使用all
内置的量子函数:
if all(word in b for word in a):
""" all words in list"""
请注意,对于长列表,这可能不是运行时效率。最好使用set
类型而不是a
列表(要搜索的列表中的列表)。
答案 6 :(得分:0)
这是一种非正则表达方式。我相信正则表达式要快得多:
>>> query = ['president', 'publicly']
>>> line = ['president', 'publicly', 'told']
>>> any(query == line[i:i+len(query)] for i in range(len(line) - len(query)))
True
>>> query = ["president" ,"pub"]
>>> any(query == line[i:i+len(query)] for i in range(len(line) - len(query)))
False
答案 7 :(得分:0)
明确比隐含更好。因为订购很重要,我会这样写下来:
query = ['president','publicly']
query_false = ['president','pub']
line = ['president','publicly','told']
query_len = len(query)
blocks = [line[i:i+query_len] for i in xrange(len(line)-query_len+1)]
blocks
包含所有相关组合以进行检查:
[['president', 'publicly'], ['publicly', 'told']]
现在您只需检查您的查询是否在该列表中:
print query in blocks # -> True
print query_false in blocks # -> False
代码的工作方式可能是用语言解释直接的解决方案,这对我来说通常是一个好兆头。如果您有长行并且性能成为问题,则可以用生成器替换生成的列表。