【python】详细解释not in,中文,代码和代码解读

目录

【python】详细解释not in,中文,代码和代码解读 

语法:

代码示例和解读:

1. 在列表中检查元素是否不存在

2. 在字符串中检查字符是否不存在

3. 在元组中检查元素是否不存在

4. 在字典中检查键是否不存在

5. 在字典中检查值是否不存在

总结:


【python】详细解释not in,中文,代码和代码解读 

在 Python 中,not in 是一个非常常用的运算符,用于检查某个元素是否不在一个容器(如列表、元组、字符串、字典等)中。

not in 运算符的作用是返回布尔值 TrueFalse,具体取决于元素是否不在容器中。

语法:

element not in container
  • element:要检查的元素。
  • container:要检查的容器,可以是列表、元组、字符串、字典等。

如果 element 不在 container 中,not in 表达式返回 True,否则返回 False

代码示例和解读:

1. 列表中检查元素是否不存在
fruits = ['apple', 'banana', 'cherry']

# 检查 'apple' 是否不在 fruits 列表中
print('apple' not in fruits)  # False,因为 'apple' 在列表中

# 检查 'orange' 是否不在 fruits 列表中
print('orange' not in fruits)  # True,因为 'orange' 不在列表中
  • 解释:在第一个 print 语句中,'apple' not in fruits 判断 'apple' 是否不在 fruits 列表中。由于 'apple' 在列表中,not in 返回 False
  • 在第二个 print 语句中,'orange' not in fruits 判断 'orange' 是否不在 fruits 列表中。由于 'orange' 不在列表中,not in 返回 True
2. 在字符串中检查字符是否不存在
text = "hello world"

# 检查字符 'h' 是否不在字符串 text 中
print('h' not in text)   # False,因为 'h' 在字符串中

# 检查字符 'z' 是否不在字符串 text 中
print('z' not in text)   # True,因为 'z' 不在字符串中
  • 解释:在第一个 print 语句中,'h' not in text 判断字符 'h' 是否不在字符串 text 中。由于 'h' 出现了,not in 返回 False
  • 在第二个 print 语句中,'z' not in text 判断字符 'z' 是否不在字符串 text 中。由于 'z' 不在字符串中,not in 返回 True
3. 在元组中检查元素是否不存在
numbers = (1, 2, 3, 4, 5)

# 检查数字 3 是否不在 numbers 元组中
print(3 not in numbers)  # False,因为 3 在元组中

# 检查数字 6 是否不在 numbers 元组中
print(6 not in numbers)  # True,因为 6 不在元组中
  • 解释:在第一个 print 语句中,3 not in numbers 判断数字 3 是否不在元组 numbers 中。由于 3 在元组中,not in 返回 False
  • 在第二个 print 语句中,6 not in numbers 判断数字 6 是否不在元组 numbers 中。由于 6 不在元组中,not in 返回 True
4. 在字典中检查键是否不存在
person = {'name': 'Alice', 'age': 25}

# 检查 'name' 是否不在字典 person 的键中
print('name' not in person)  # False,因为 'name' 是字典中的键

# 检查 'gender' 是否不在字典 person 的键中
print('gender' not in person)  # True,因为 'gender' 不是字典中的键
  • 解释:在第一个 print 语句中,'name' not in person 判断 'name' 是否不在字典 person 的键中。由于 'name' 是字典中的键,not in 返回 False
  • 在第二个 print 语句中,'gender' not in person 判断 'gender' 是否不在字典 person 的键中。由于 'gender' 不是字典中的键,not in 返回 True
5. 在字典中检查值是否不存在

如果你需要检查字典中的某个是否不存在,not in 需要与 dict.values() 一起使用。

person = {'name': 'Alice', 'age': 25}

# 检查 'Alice' 是否不在字典 person 的值中
print('Alice' not in person.values())  # False,因为 'Alice' 是字典中的值

# 检查 'Bob' 是否不在字典 person 的值中
print('Bob' not in person.values())  # True,因为 'Bob' 不是字典中的值
  • 解释:在第一个 print 语句中,'Alice' not in person.values() 判断 'Alice' 是否不在字典 person 的值中。由于 'Alice' 是字典中的值,not in 返回 False
  • 在第二个 print 语句中,'Bob' not in person.values() 判断 'Bob' 是否不在字典 person 的值中。由于 'Bob' 不在字典的值中,not in 返回 True

总结:

  • not in 运算符的作用是检查元素是否不在容器中,并返回布尔值 TrueFalse
  • 它可以用于不同类型的容器,包括列表、元组、字符串和字典等。
  • 在字典中,not in 默认检查元素是否是字典的键,如果需要检查,则需要与 dict.values() 一起使用。

not in 是一个非常简洁、直观的运算符,广泛应用于条件判断和循环中。

你可能感兴趣的:(笔记,算法,python,开发语言)