简体   繁体   English

如何验证任何字符串列表是否在另一个数组中并在 Python 中附加该数组

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

I have an array of strings in Python:我在 Python 中有一个字符串数组:

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

I want to append all the strings that have 'cat' or 'dog'.我想附加所有带有“cat”或“dog”的字符串。 Ideal result is:理想的结果是:

list=['Thatis_acat','Thoseare_dogs']

My code is:我的代码是:

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

But the result is actually blank 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)

This solution involves conditional list comprehension此解决方案涉及条件列表理解

It basically says make a list R, so that it includes every entry from A if any pattern from L can be found in that entry.它基本上是说制作一个列表 R,以便它包含来自 A 的每个条目,如果可以在该条目中找到来自 L 的任何模式。

You can use re :您可以使用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))

This could be done using a list comprehension instead of using filter but it seemed more appropriate:这可以使用列表理解来完成,而不是使用过滤器,但它似乎更合适:

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

Result: (same for both filter and list comp)结果:(过滤器和列表组合相同)

['Thatis_acat', 'Thoseare_dogs']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM