要检查某些元素是否不在序列、列表、字符串、元组或集合中,请使用not in 操作符。not in 操作符与 in 操作符完全相反。
Python 中的 in 操作符检查一个指定的值是否是一个序列的组成元素。
Python 不在操作符
not in 是一个内置的 Python 操作符,它检查指定的值是否存在于给定的序列中,但是它的值与 in 操作符相反。
not in 操作符返回一个布尔值作为输出。它要么返回True,要么返回False。
listA = [11, 21, 29, 46, 19]
stringA = "Hello! This is AppDividend"
tupleA = (11, 22, 33, 44)
print(19 not in listA)
print("is" not in stringA)
print(55 not in tupleA)
输出
False
False
True
当你在一个条件中使用not in操作符时,语句会返回一个布尔值,评价为True或False。
在我们的例子中,首先,我们检查列表中的元素。它返回False,因为19是在列表A中。
然后stringA包含**"is "作为子串,这就是为什么返回False**。
当在序列中找到指定的值时,该语句返回True。而当它没有被找到时,我们得到一个False。
字典中 "在 "和 "不在 "操作符的作用
字典不是序列,因为字典是基于键来索引的。让我们看看如何在字典中使用,不在操作符?如果他们这样做,他们如何评估条件?
让我们试着用一个例子来理解。
dict1 = {11: "eleven", 21: "twenty one", 46: "fourty six", 10: "ten"}
print("eleven" in dict1)
print("eleven" not in dict1)
print(21 in dict1)
print(21 not in dict1)
print(10 in dict1)
print(10 not in dict1)
输出
False
True
True
False
True
False
本教程到此结束。
The postPython Not In Operator:完整指南》首次出现在AppDividend上。