[英]How to check if element in array contains any values from a list Python
I have a list of words:我有一个单词列表:
list1 = ['foo', 'baz', 'bat']
And an array of strings:和一个字符串数组:
list2 = ['foo word word word', 'word baz word word', 'word word word word', 'word word bat word']
string_arr = np.array(list2)
I want to enumerate through the array and return a boolean if the element in the array contains any of the values in the list.如果数组中的元素包含列表中的任何值,我想枚举数组并返回 boolean 。 The output to be a list of booleans:
output 是一个布尔值列表:
[True, True, False, True]
Right now all I have is this code which just gives me a list of indices, which I don't want:现在我所拥有的只是这段代码,它只给了我一个我不想要的索引列表:
idx_mask = [idx for idx, element in enumerate(string_arr) if any(x in element for x in list1)]
How can I just get a list of booleans?我怎样才能得到一个布尔值列表?
print([any(x in element for x in list1) for element in list2])
To find only full word matches, you should match them to each string from list2
split by space to make a word array:要仅查找完整的单词匹配项,您应该将它们与
list2
中的每个字符串匹配,并按空格分隔以创建一个单词数组:
print([any(x in element.split(' ') for x in list1) for element in list2])
Test:测试:
list1 = ['foo', 'baz', 'bat', 'w']
list2 = ['foo word word word', 'word baz word word', 'word word word word', 'word word bat word']
results are:结果是:
[True, True, False, True]
which is the expected result.这是预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.