Python 成员运算符
成员运算符用于检测元素是否存在于序列或集合中,返回布尔值。
基本语法
Python
# in 运算符:元素存在返回 True
value in container
# not in 运算符:元素不存在返回 True
value not in container
使用示例
列表与元组
Python
fruits = ['apple', 'banana', 'orange']
print('apple' in fruits) # True
print('grape' in fruits) # False
print('grape' not in fruits) # True
# 元组同理
colors = ('red', 'green', 'blue')
print('red' in colors) # True
字符串
Python
text = "Hello, Python"
print('Python' in text) # True
print('python' in text) # False(区分大小写)
print('java' not in text) # True
字典
Python
person = {'name': 'Alice', 'age': 25}
# 默认检查键
print('name' in person) # True
print('Alice' in person) # False
# 检查值
print('Alice' in person.values()) # True
# 检查键值对
print(('name', 'Alice') in person.items()) # True
集合
Python
nums = {1, 2, 3, 4, 5}
print(3 in nums) # True
print(6 not in nums) # True
性能对比
| 数据结构 | 查找时间复杂度 |
|---|---|
| 列表/元组 | O(n) |
| 字典/集合 | O(1) |
对于频繁的成员检查,优先使用集合或字典,性能更优。
要点总结
in判断元素存在,not in判断元素不存在- 字典默认检查键,需用
.values()或.items()检查值 - 集合和字典的成员检查效率远高于列表
- 字符串检查区分大小写
📝 发现内容有误?点击此处直接编辑