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