问题
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