gpt4 book ai didi

python - 查找列表中的任何字符串元素是否包含在字符串列表中

转载 作者:太空狗 更新时间:2023-10-30 02:30:59 24 4
gpt4 key购买 nike

我需要创建一个脚本来根据其中是否存在字符串列表来接受/拒绝某些文本。

我有一个应该用作拒绝机制的关键字列表:

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 的方法来解决这个问题?

最佳答案

您可以使用 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
>>>

关于python - 查找列表中的任何字符串元素是否包含在字符串列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com