Python中的 not in 运算符

Python中的 not in 运算符

Python中的 not in 运算符

概述

Python 是一种非常强大且灵活的编程语言,它提供了许多用于处理数据和控制流程的内置操作符。其中之一是”not in” 运算符,它用于检查一个值是否不在给定的容器(例如列表、元组、集合或字符串)中。

在本文中,我们将详细解释 “not in” 运算符的用法和工作原理,以及它在实际编程中的一些常见应用。

基本语法

“not in”运算符的基本语法如下:

value not in container

其中,value是要检查的值,而container是要搜索的容器。如果value不在container中,该表达式将返回True;如果valuecontainer中,该表达式将返回False

列表中的应用

我们首先来看一下如何在列表中使用 “not in” 运算符。

示例代码

fruits = ['apple', 'banana', 'orange', 'grape']

# 检查字符串是否存在于列表中
print('apple' not in fruits)  # 输出 False
print('watermelon' not in fruits)  # 输出 True

# 检查数字是否存在于列表中
print(3 not in fruits)  # 输出 True
print(2 not in fruits)  # 输出 True

运行结果

False
True
True
True

从上述示例中可以看出,我们可以用 “not in” 运算符来检查一个值是否不在列表中,并通过输出验证。

元组中的应用

与列表类似,我们也可以在元组中使用 “not in” 运算符。

示例代码

colors = ('red', 'green', 'blue', 'yellow')

# 检查字符串是否存在于元组中
print('red' not in colors)  # 输出 False
print('purple' not in colors)  # 输出 True

# 检查数字是否存在于元组中
print(2 not in colors)  # 输出 True
print(1 not in colors)  # 输出 True

运行结果

False
True
True
True

通过上述示例,我们可以看到 “not in” 运算符可用于元组中的相同方式。它可以帮助我们判断一个值是否不存在于元组中。

集合中的应用

集合是 Python 中的一种无序且不重复的数据结构,我们同样可以在集合中使用 “not in” 运算符。

示例代码

prime_numbers = {2, 3, 5, 7, 11}

# 检查数字是否存在于集合中
print(3 not in prime_numbers)  # 输出 False
print(4 not in prime_numbers)  # 输出 True

# 检查字符串是否存在于集合中
print('apple' not in prime_numbers)  # 输出 True
print('orange' not in prime_numbers)  # 输出 True

运行结果

False
True
True
True

通过上述示例,我们可以看到 “not in” 运算符同样适用于集合。我们可以使用它来检查一个值是否不存在于集合中。

字符串中的应用

我们还可以在字符串中使用 “not in” 运算符来检查子字符串是否存在。

示例代码

text = "Hello, World!"

# 检查子字符串是否存在于字符串中
print('Hello' not in text)  # 输出 False
print('Python' not in text)  # 输出 True

# 检查字符是否存在于字符串中
print('H' not in text)  # 输出 False
print('Z' not in text)  # 输出 True

运行结果

False
True
False
True

通过上述示例,我们可以看到在字符串中使用 “not in” 运算符可以很方便地检查一个子字符串或字符是否不存在于给定的字符串中。

结论

在本文中,我们详细了解了 Python 中的 “not in” 运算符以及它在不同类型的容器中的应用。它非常适用于判断一个值是否不在给定的容器中。我们在列表、元组、集合和字符串的示例中展示了它的用法,并通过输出进行了验证。

不过,请记住,”not in” 运算符只能用于可迭代的容器(例如列表、元组、集合和字符串),对于其他类型的容器(例如字典)不适用。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程