全部学科
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列表基础
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码