【问题标题】:how to check if a list of sub-strings is in a list (python)如何检查子字符串列表是否在列表中(python)
【发布时间】:2019-02-04 02:23:14
【问题描述】:

我有一个名为keywords的字符串列表:

keywords = ["123", "hello there"]

我想看看这些字符串是否在此列表中strArr

strArr = ["123", "hello there", "another"]

我试过了:

if all (keyword in strArr for keyword in keywords):
    print("True")
else:
    print("False")

如果我有完整的字符串,它会工作并返回 true,但是当我尝试找到这样的子字符串时会失败:

keywords = ["123", "hello"]

【问题讨论】:

    标签: python string list csv substring


    【解决方案1】:

    任何时候你有一组事物并且你正在测试成员/交叉等,你应该考虑使用sets。上手之后就轻松多了。

    请看下面的例子:

    In [46]: keywords = {"123", "hello there"}                                                  
    In [47]: strArr = {"123", "hello there", "another"}                                         
    In [48]: keywords & strArr   # intersection                                                               
    Out[48]: {'123', 'hello there'}
    In [49]: keywords.issubset(strArr)                                                          
    Out[49]: True
    In [50]: if (keywords & strArr):  # do something
    

    在最后一行,如果intersection 中有任何内容,则值为True,否则为False

    【讨论】:

      【解决方案2】:

      您可以检查每个关键字是否 strArr中的任何项目中:

      print( all ( any( (keyword in strItem for strItem in strArr) ) for keyword in keywords ))
      

      注意:如果您正在检查条件并打印结果,您可以只打印条件本身。

      【讨论】:

        【解决方案3】:

        很多人已经回答了这个问题。既然我试过了,我会发布我的答案。

        print ([i for i in strArr if any(j in keywords for j in i.split())]) # Outer For loop: "i for i in strArr", Inner For Loop with If any condition(): "if any(j in keywords for j in i.split())"
        

        我希望这很重要。 :)

        【讨论】:

          猜你喜欢
          • 2013-04-29
          • 1970-01-01
          • 1970-01-01
          • 2021-02-15
          • 1970-01-01
          • 2018-06-06
          • 2017-04-27
          • 1970-01-01
          • 2015-01-22
          相关资源
          最近更新 更多