【问题标题】:Find if any string element in list is contained in list of strings查找列表中的任何字符串元素是否包含在字符串列表中
【发布时间】:2014-06-13 21:03:22
【问题描述】:

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

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

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

如果在我下面提供的列表中找到任何这些字符串元素,则该列表应标记为 rejected。这是应该检查的列表:

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

【问题讨论】:

标签: python list


【解决方案1】:

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

【讨论】:

  • 这真的回答了这个问题吗?如果在c_lst 中找到k_out 列表中的任何单词,OP 希望该列表被拒绝。如果设计正确,上面的代码应该返回 false
  • @Smac89 - 这取决于您如何解释问题。 OP 说“如果找到任何这些 string 元素 ...该列表应标记为已拒绝”。我理解“字符串元素”是指k_out 中的子字符串。您还会注意到我的解决方案产生与 OP 相同的输出。这只是一种更紧凑的方式。
  • 哎呀,我没有看到完整列表,因为我是在手机上查看的。好的,我明白为什么现在这样了
猜你喜欢
  • 2010-10-04
  • 1970-01-01
  • 2017-11-20
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多