检查字符串是否不包含列表中的字符串

时间:2019-10-31 10:59:13

标签: python

我有以下代码:

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。

5 个答案:

答案 0 :(得分: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)]

答案 1 :(得分:0)

如果您不希望这些字母中的任何一个出现在字符串中,则应使用:

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

您的代码在这里工作,只是使用了不同的变量名:

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 列表元素是否为真,而不仅仅是其中的任何一个。

答案 4 :(得分:0)

尝试一下

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