pin_drop当前位置:知识文库 ❯ 图文
Python成员运算符in和not
概述
成员运算符用于判断某个值是否属于某个序列或集合,是Python中非常实用的运算符。Python提供了in和not in两个成员运算符,它们可以在字符串、列表、元组、集合、字典等数据类型中使用。本节将详细介绍成员运算符的用法及其在不同数据类型中的行为。
in运算符
in运算符用于判断某个值是否存在于指定的序列中,如果存在返回True,否则返回False。
基本语法
代码示例
value in sequence在字符串中使用
代码示例
print("h" in "hello")
print("x" in "hello")
print("ell" in "hello")
print("Hello" in "hello")输出:
代码示例
True
False
True
False提示:字符串的
in运算判断的是子串,即"ell" in "hello"为True。
在列表中使用
代码示例
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)
print("grape" in fruits)
print(3 in [1, 2, 3, 4, 5])输出:
代码示例
True
False
True在元组中使用
代码示例
colors = ("red", "green", "blue")
print("red" in colors)
print("yellow" in colors)输出:
代码示例
True
False在集合中使用
代码示例
numbers = {1, 2, 3, 4, 5}
print(3 in numbers)
print(10 in numbers)输出:
代码示例
True
False性能提示:集合的
in运算时间复杂度为O(1),而列表和元组为O(n),在频繁查找时优先使用集合。
在字典中使用
在字典中,in运算符判断的是键是否存在:
代码示例
student = {"name": "Alice", "age": 25, "score": 95}
print("name" in student)
print("Alice" in student)
print("score" in student)输出:
代码示例
True
False
Truenot in运算符
not in运算符是in的否定形式,判断某个值是否不存在于指定序列中。
基本语法
代码示例
value not in sequence使用示例
代码示例
fruits = ["apple", "banana", "cherry"]
print("grape" not in fruits)
print("apple" not in fruits)
text = "Hello World"
print("xyz" not in text)
print("World" not in text)
numbers = {1, 2, 3}
print(4 not in numbers)
print(2 not in numbers)输出:
代码示例
True
False
True
False
True
False
not in与not ... in的等价性
value not in sequence与not value in sequence完全等价:
代码示例
fruits = ["apple", "banana"]
print("grape" not in fruits)
print(not "grape" in fruits)输出:
代码示例
True
True最佳实践:推荐使用
not in,语义更清晰。
在不同数据类型中的使用
性能对比
range中的成员判断
代码示例
print(5 in range(10))
print(15 in range(10))
print(100 in range(0, 200, 2))
print(101 in range(0, 200, 2))输出:
代码示例
True
False
True
False提示:
range的in运算使用数学计算判断,时间复杂度为O(1),不会遍历整个范围。
嵌套结构中的使用
代码示例
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([1, 2, 3] in matrix)
print([1, 2] in matrix)
print(5 in matrix)输出:
代码示例
True
False
False注意:
5 in matrix为False,因为in只检查第一层,不会递归查找。
自定义对象中的使用
通过实现__contains__方法,可以让自定义类支持in运算符:
代码示例
class NumberRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __contains__(self, item):
return self.start <= item <= self.end
rng = NumberRange(1, 100)
print(50 in rng)
print(150 in rng)输出:
代码示例
True
False运算符表格
各数据类型行为总结
代码示例
示例1:用户权限验证
代码示例
valid_users = ["admin", "editor", "viewer", "moderator"]
banned_users = ["spam_bot", "hacker"]
username = "editor"
if username in valid_users and username not in banned_users:
print(f"欢迎, {username}!")
elif username in banned_users:
print(f"用户 {username} 已被封禁")
else:
print("未知用户")示例2:敏感词过滤
代码示例
sensitive_words = {"暴力", "色情", "赌博", "毒品"}
content = "这是一条正常的评论内容"
has_sensitive = any(word in content for word in sensitive_words)
print(f"包含敏感词: {has_sensitive}")
content2 = "这条评论包含暴力内容"
has_sensitive2 = any(word in content2 for word in sensitive_words)
print(f"包含敏感词: {has_sensitive2}")示例3:列表去重
代码示例
numbers = [1, 3, 2, 3, 4, 1, 5, 2, 6]
unique = []
for num in numbers:
if num not in unique:
unique.append(num)
print(f"原始列表: {numbers}")
print(f"去重后: {unique}")示例4:字典键值判断
代码示例
config = {"host": "localhost", "port": 3306, "debug": True}
if "host" in config:
print(f"主机: {config['host']}")
if "timeout" not in config:
config["timeout"] = 30
print("已设置默认超时时间")
print(f"配置: {config}")注意事项
字典判断的是键:
in在字典中判断键是否存在,不是值。判断值需要用value in dict.values()。性能差异:集合和字典的查找是O(1),列表和元组是O(n)。大量查找时优先使用集合。
字符串判断子串:字符串的
in判断的是子串,不是单个字符。"ab" in "abc"为True。不递归查找:
in只检查一层,不会递归查找嵌套结构中的元素。None也可以判断:
None in [1, None, 3]为True。
小结
本节我们学习了:
-
in运算符:判断值是否存在于序列中,返回布尔值
-
not in运算符:判断值是否不存在于序列中,是
in的否定形式 -
不同数据类型:字符串判断子串,字典判断键,集合查找最快
-
性能差异:集合/字典O(1),列表/元组O(n),range O(1)
-
自定义支持:通过
__contains__方法让自定义类支持in运算
成员运算符是Python中简洁而强大的工具,善用它们可以让代码更加清晰和高效。
练习题
练习1
编写程序,输入一个字符串,判断它是否是回文字符串(正读和反读相同)。使用in运算符或其他方法实现。
练习2
给定两个列表list1 = [1, 2, 3, 4, 5]和list2 = [4, 5, 6, 7, 8],使用成员运算符找出它们的交集和差集(不使用集合运算符)。
常见问题
Python中in和not in有什么区别?
in用于判断值是否存在于序列中,存在返回True;not in是其否定形式,判断值是否不存在于序列中,不存在返回True。两者功能相反但用法完全相同。
在字典中使用in运算符判断的是键还是值?
在字典中,in运算符默认判断的是键(key)是否存在,而不是值。如果需要判断值是否存在,需要使用value in dict.values()。
为什么在频繁查找时推荐使用集合而不是列表?
集合的in运算时间复杂度为O(1),因为使用哈希表实现,直接通过哈希值定位元素。而列表和元组需要从头到尾遍历查找,时间复杂度为O(n)。当数据量大且需要频繁查找时,集合的性能优势非常明显。
成员运算符可以递归查找嵌套结构中的元素吗?
不可以。in运算符只检查第一层,不会递归查找。例如在二维列表[[1,2,3],[4,5,6]]中,5 in matrix返回False,因为5不在第一层,需要遍历每一层才能找到。
如何让自定义类支持in运算符?
只需在类中实现__contains__魔术方法。该方法接收一个参数(要查找的元素),返回布尔值表示是否存在。例如:def __contains__(self, item): return self.start <= item <= self.end。
本文涉及AI创作
内容由AI创作,请仔细甄别