在字符串列表中查找字符串列表,返回布尔值 [英] find list of strings in list of strings, return boolean
问题描述
我正在尝试使用 python 中的字符串列表,但不知何故我找不到好的解决方案.我想在字符串列表中查找字符串列表并返回布尔值:
I am trying to work with lists of strings in python and somehow I can't find a good solution. I want to find a list of strings within a list of strings and return boolean values:
import re
sentences = ['Hello, how are you?',
'I am fine, how are you?',
'I am fine too, thanks']
bits = ['hello', 'thanks']
re.findall(sentences, bits)
# desired output: [True, False, True]
因此,如果句子字符串包含一个或多个位,我想获得一组带有 True 的布尔值.我也试过
So I want to get an array of booleans with True, if the sentences string contains one or more of the bits. I also tried
bits = r'hello|thanks'
但我总是收到错误'unhashable type:'list''.我尝试将列表转换为数组,但错误只是显示不可哈希类型:‘列表’".如有任何帮助,我将不胜感激!
but I always get the error 'unhashable type: 'list''. I tried converting the lists to arrays, but then the error just says 'unhashable type: 'list''. I would be grateful for any help!
推荐答案
一种选择是使用嵌套列表推导式:
One option is to use a nested list comprehension:
sentences = ['Hello, how are you?',
'I am fine, how are you?',
'I am fine too, thanks']
bits = ['hello', 'thanks']
[any(b in s.lower() for b in bits) for s in sentences]
# returns:
[True, False, True]
如果你想使用正则表达式,你需要将bits
与一个管道符连接起来,但你仍然需要单独检查sentences
中的每个句子.
If you want to use a regular expression, you need to join bits
with a pipe character, but you will still need to check each sentence in sentences
individually.
[bool(re.search('|'.join(bits), s, re.IGNORECASE)) for s in sentences]
# returns:
[True, False, True]
这篇关于在字符串列表中查找字符串列表,返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!