在列表理解/生成器表达式中,`x in y`的对立面是什么?

2024-10-06 12:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我举了一个这样的例子:

identified_characters = ["a","c","f","h","l","o"]
word = "alcachofa#"
if any(character in word for character not in identified_characters):
    print("there are unidentified characters inside the word")
else:
    print("there aren't unidentified characters inside the word")

但是not带来了语法错误,所以我想如果有一个out(我猜是in的相反)函数,理论上你可以更改not in并保留语法

我还认为给定结果的逻辑应该是any函数的对立面,但我向上看时发现,ppl的对立面应该是not all,在这种情况下,在这里不起作用


Tags: the函数innotany例子wordthere
2条回答

您不能循环使用不在identified_characters中的所有可能项目;莫名其妙地有很多。这在概念上甚至没有意义

要实现您想要的(检查word中是否有未识别的字符(不在identified_characters中的字符),您必须循环word,而不是identified_characters的补码

identified_characters = {"a", "c", "f", "h", "l", "o"}

word = "alcachofa#"
if any(character not in identified_characters for character in word):
    print("there are unidentified characters inside the word")
else:
    print("there aren't unidentified characters inside the word")

不要在for语句中使用not,而是在character in word部分使用它

identified_characters=["a","c","f","h","l","o"]
word="alcachofa#"
if any(character not in identified_characters for character in word):
    print("there are unidentified characters inside the word")
else:
    print("there aren't unidentified characters inside the word")

For循环可以使用in,但不能使用not in,因为它们不知道not in的意思!For循环用于遍历列表或任何iterable,不能遍历iterable中不存在的内容,因为它们不知道什么不在iterable中。您还可以通过以下方式使用not all

相关问题 更多 >