[英]Find matching substrings in two lists
由于您从str.contains
标记了pandas
解决方案
#S_A=pd.Series(list_A)
#S_B=pd.Series(list_B)
S_B[S_B.apply(lambda x : S_A.str.contains(x)).any(1)]
Out[441]:
0 hell
2 here
dtype: object
这是一种方法。 使用list comprehension
。
list_A = ['hello','there','you','are']
list_B = ['hell','is','here']
jVal = "|".join(list_A) # hello|there|you|are
print([i for i in list_B if i in jVal ])
输出:
['hell', 'here']
IIUC:我会用Numpy
import numpy as np
from numpy.core.defchararray import find
a = np.array(['hello', 'there', 'you', 'are', 'up', 'date'])
b = np.array(['hell', 'is', 'here', 'update'])
bina = b[np.where(find(a[:, None], b) > -1)[1]]
ainb = a[np.where(find(b, a[:, None]) > -1)[0]]
np.append(bina, ainb)
array(['hell', 'here', 'up', 'date'], dtype='<U6')
list_A = ['hello','there','you','are']
list_B = ['hell','is','here']
List_C = []
for a in list_A:
for b in list_B:
print(a,"<->",b)
if a in b:
List_C.append(a)
if b in a:
List_C.append(b)
print(List_C)
对于娱乐,这是使用正则表达式的答案!
import re
matches = []
for pat in list_B:
matches.append(re.search(pat, ' '.join(list_A)))
matches = [mat.group() for mat in matches if mat]
print(matches)
# ['hell', 'here']
这将为找到的每个匹配项返回一个匹配对象,该对象的实际字符串由match.group()
找到。 需要注意的是,如果没有发现匹配(如在你的第二个元素的情况下list_B
),你会得到一个None
在matches
,因此需要添加的if mat
在列表理解的结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.