1. 什么是 in?
在 Python 中,in 是一个关键字,主要用于两种场景:
- 成员测试(Membership Test):判断某个值是否存在于序列或集合中。
- 循环遍历(Iteration):配合
for语句遍历可迭代对象。
2. 成员测试:判断元素是否存在
使用 value in container 返回 True 或 False。
示例 1:列表(List)
fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits) # True
print('orange' in fruits) # False
示例 2:字符串(String)
text = "Hello, world!"
print('world' in text) # True
print('Python' in text) # False
示例 3:字典(Dict)
对字典使用 in 默认检查的是键(key),不是值(value)。
person = {'name': 'Alice', 'age': 25}
print('name' in person) # True
print('Alice' in person) # False
print('Alice' in person.values()) # True
示例 4:集合(Set)
nums = {1, 2, 3, 4}
print(3 in nums) # True
print(5 in nums) # False
3. 遍历:在 for 循环中使用 in
for item in iterable: 是 Python 最常见的循环结构。
遍历列表
colors = ['red', 'green', 'blue']
for color in colors:
print(color)
遍历字符串
for char in "Python":
print(char)
遍历字典的键
for key in person:
print(key, person[key])
遍历字典的键值对
for key, value in person.items():
print(f"{key}: {value}")
4. 注意事项与技巧
in的时间复杂度因数据结构而异:- 列表/元组:O(n)
- 集合/字典键:平均 O(1)
- 不要对大型列表频繁使用
in,考虑转为set提升性能。 - 字符串的
in是子串匹配,区分大小写。
5. 小测验(JavaScript 交互演示)
点击按钮查看代码运行结果: