我需要创建一个脚本来根据是否存在字符串列表来接受/拒绝某些文本。
我有一个应该用作拒绝机制的关键字列表:
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']
这就是我所拥有的:
flag_r = False
for text in k_out:
for lst in c_lst:
if text in lst:
flag_r = True
是否有更多的 pythonic 方式来解决这个问题?
答案 0 :(得分:6)
您可以使用any
和generator 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
>>>