Find if any string element in a list is contained in a list of strings

I need to create a script to accept / reject some text based on whether a list of strings is present in it.

I have a list of keywords that should be used as a rejection mechanism:

k_out = ['word1', 'word2', 'some larger text']

If any of these string elements are found in the list below, the list should be marked as rejected. This is the list to check:

c_lst = ['This is some text that contains no rejected word', 'This is some larger text which means this list should be rejected']

This is what I have:

flag_r = False
for text in k_out:
    for lst in c_lst:
        if text in lst:
            flag_r = True

is there a more pythonic way of doing this?

+4
source share
1 answer

You can use a generatorany expression :

>>> k_out = ['word1', 'word2', 'some larger text']
>>> c_lst = ['This is some text that contains no rejected word', 'This is some larger text which means this list should be rejected']
>>> any(keyword in string for string in c_lst for keyword in k_out)
True
>>>
+6
source

Source: https://habr.com/ru/post/1544534/


All Articles