簡體   English   中英

在兩個列表中查找匹配的子字符串

[英]Find matching substrings in two lists

我有兩個列表:A和B。列表長度不同,並且都包含字符串。 在兩個列表中匹配子字符串的最佳方法是什么?

list_A = ['hello','there','you','are']
list_B = ['say_hellaa','therefore','foursquare']

我想要一個名為list_C的匹配子字符串的列表,其中包含:

list_C = ['hell','there','are']

我遇到了這個答案,但它要求我有一個匹配子字符串的列表。 有沒有一種方法可以無需手動創建匹配子字符串列表就可以得到想要的?

也無濟於事,因為第二個列表包含子字符串。

由於您從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 ),你會得到一個Nonematches ,因此需要添加的if mat在列表理解的結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM