find list of strings in list of strings, return boolean

隐身守侯 提交于 2021-02-05 11:34:26

问题


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]

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'

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!


回答1:


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]

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]


来源:https://stackoverflow.com/questions/55443169/find-list-of-strings-in-list-of-strings-return-boolean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!