首页/ 学科题库/ python/ Python 成员运算符
python 实战教程

Python 成员运算符

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() 检查值
  • 集合和字典的成员检查效率远高于列表
  • 字符串检查区分大小写
想在手机上练这篇的配套题目?
使用微信 卷王开发者小程序/App,首页顶部扫一扫识别下方二维码,即可解锁本讲对应真题与错题本。
了解产品 App
← 上一篇 Python布尔类型与逻辑值 下一篇 → Python列表基础