【问题标题】:Check if string does not contain strings from the list检查字符串是否不包含列表中的字符串
【发布时间】:2020-02-26 17:28:08
【问题描述】:

我有以下代码:

mystring = ["reddit", "google"]
mylist = ["a", "b", "c", "d"]
for mystr in mystring:
    if any(x not in mystr for x in mylist):
        print(mystr)

我希望这应该只返回"google"。但由于某种原因,它同时返回 "reddit""google"

【问题讨论】:

  • if all(x not in mystr for x in mylist): ?
  • 在 python 中,对变量使用snake_case 是一个惯例。此外,如果您有一个列表,请将变量名称设为复数,例如my_strings。这意味着您不必说像for mystr in mystring 这样的奇怪的话。这些只是挑剔,但遵循这些约定可以更容易理解您自己的代码

标签: python


【解决方案1】:

您对anynot in 的使用自相矛盾。您想像这样检查all

if all(x not in mystr for x in mylist):
    print mystr

或者只是检查not any(我认为这更具可读性):

if not any(x in mystr for x in mylist):
    print mystr

如果您使用列表推导式(但这只是个人喜好,或者您更喜欢打印一行结果),那么这两个版本都可以是单行的(而不是循环)每个结果一行):

mystring = ["reddit", "google"]
mylist = ["a", "b", "c", "d"]
print [s for s in mystring if not any(x in s for x in mylist)]

【讨论】:

    【解决方案2】:

    如果您不希望这些字母出现在您的字符串中,那么您应该使用:

    all(x not in mystr for x in mylist)
    

    而不是any:

    mystring = ["reddit", "google"]
    mylist = ["a", "b", "c", "d"]
    for mystr in mystring:
      if all(x not in mystr for x in mylist):
        print mystr
    

    仅打印

    google
    

    【讨论】:

      【解决方案3】:

      为确保输入字符串不包含列表中的 any 字符,您的条件应为:

      ...
      if not any(x in mystr for x in mylist):
      

      【讨论】:

        【解决方案4】:

        这是您的代码,只是使用不同的变量名:

        words = ["reddit", "google"]
        chars = ["a", "b", "c", "d"]
        for word in words:
            print(word,":",[char not in word for char in chars]) #explanation help
            if all(char not in word for char in chars):
                print("none of the characters is contained in",word)
        

        它的输出:

        reddit : [True, True, True, False]
        google : [True, True, True, True]
        none of the characters is contained in google
        

        如您所见,您只需将any 更改为all。 这是因为您要测试单词中是否不包含任何字符,因此输出中显示的 all 列表元素是否为真,而不仅仅是其中任何一个。

        【讨论】:

          【解决方案5】:

          试试这个

          s = ["reddit","google"]
          l = ["a","b","c","d"]
          for str in s:
              if all(x not in str for x in l):
                 print(str)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-10-04
            • 2019-04-11
            • 1970-01-01
            • 2013-10-26
            • 2013-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-09
            相关资源
            最近更新 更多