全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 5 分钟 ✍️ juanwangdev

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() 检查值
  • 集合和字典的成员检查效率远高于列表
  • 字符串检查区分大小写

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python类型转换
下一篇 → Python元组基础
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库