簡體   English   中英

如何驗證任何字符串列表是否在另一個數組中並在 Python 中附加該數組

[英]How to verify any of lists of strings are in another array and append the array in Python

我在 Python 中有一個字符串數組:

array=array(['Thisis_anapple','Thatis_acat', 'Thoseare_dogs'], dtype=object)

我想附加所有帶有“cat”或“dog”的字符串。 理想的結果是:

list=['Thatis_acat','Thoseare_dogs']

我的代碼是:

list=[]
if any(x in array for x in ['cat', 'dog']):
    list=list.append(x)
print(list)

但結果實際上是空白列表。

A = ['Thisis_anapple','Thatis_acat', 'Thoseare_dogs']
L = ['cat', 'dog']
R = [entry for entry in A if any(l in entry for l in L)]
print(R)

此解決方案涉及條件列表理解

它基本上是說制作一個列表 R,以便它包含來自 A 的每個條目,如果可以在該條目中找到來自 L 的任何模式。

您可以使用re

import re

array = ['Thisis_anapple','Thatis_acat', 'Thoseare_dogs']
words = ['cat', 'dog']
to_find = re.compile('|'.join(words))

result = list(filter(to_find.search, array))

這可以使用列表理解來完成,而不是使用過濾器,但它似乎更合適:

result = [s for s in array if to_find.search(s)]

結果:(過濾器和列表組合相同)

['Thatis_acat', 'Thoseare_dogs']

暫無
暫無

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

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