[英]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.