我有 2 个清单。
a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']
我想迭代 b 的每个元素并检查该字符串是否存在于列表 a 中。我怎样才能做到这一点 ?
对于上面的示例输出将是:
# is
a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']
import re
for elem in b:
for test in a:
if re.search(r'\b' + re.escape(elem) + r'\b', test):
print elem
使用列表理解:
>>> a = ['this;mango', 'is:red', 'test;cat']
>>> b = ['man', 'is', 'can']
>>>
>>> import re
>>> [elem for elem in b if any(re.search(r'\b' + re.escape(elem) + r'\b', test) for test in a)]
['is']
另一个带有map
和lambda
避免explicit
循环的版本a
:
>>> [elem for elem in b if any(map(lambda test: re.search(r'\b' + re.escape(elem) + r'\b', test), a))]
['is']
In [13]: words = set(reduce(operator.add, (re.split(r'[:;]', s) for s in a)))
In [14]: words
Out[14]: set(['this', 'is', 'cat', 'mango', 'test', 'red'])
In [15]: [w for w in b if w in words]
Out[15]: ['is']
我认为你真的必须在 a 中指定你的分隔符,否则也应该找到“man”。
>>> a = ['this;mango', 'is:red', 'test;cat']
>>> b = ['man', 'is', 'can']
>>> [elem for elem in b if elem in " ".join(a)]
['man', 'is']
采用@NPE 的解决方案并希望非单词字符\W
可以。
In [221]: a = ['this;mango', 'is:red', 'test;cat']
In [222]: right = set(reduce(operator.add, list(re.split(r'[\W]', s) for s in a)))
In [223]: right
Out[223]: set(['this', 'is', 'cat', 'mango', 'test', 'red'])
In [224]: left = set(['man', 'is', 'can'])
In [225]: left
Out[225]: set(['is', 'can', 'man'])
In [226]: left & right
Out[226]: set(['is'])
这个怎么样?
[i for i in b if any(i in re.split(r'\W', j) for j in a)]
您可以组合 b 的元素以避免第二个循环:
import re
a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']
def words_in_strings(words, strings):
pat = re.compile('|'.join(words))
for i in strings:
m = pat.search(i)
if m:
yield m.group(0)
for i in words_in_strings(b, a):
print i