在 Python 中,in 运算符用于检查某个值是否存在于一个序列(如字符串、列表、元组、集合或字典)中。in 运算符返回一个布尔值:如果值存在于序列中,则返回 True;否则返回 False。
用法示例
字符串:
python
复制代码
text = "Hello, world!"
print('H' in text) # 输出: True
print('z' in text) # 输出: False
列表:
python
复制代码
fruits = ['apple', 'banana', 'cherry']
展开剩余69%print('banana' in fruits) # 输出: True
print('grape' in fruits) # 输出: False
元组:
python
复制代码
numbers = (1, 2, 3, 4, 5)
print(3 in numbers) # 输出: True
print(10 in numbers) # 输出: False
集合:
python
复制代码
numbers_set = {1, 2, 3, 4, 5}
print(3 in numbers_set) # 输出: True
print(10 in numbers_set) # 输出: False
字典(检查键而非值):
python
复制代码
person = {'name': 'Alice', 'age': 30}
print('name' in person) # 输出: True
print('age' in person) # 输出: True
print('Alice' in person) # 输出: False (检查的是键,不是值)
注意事项
对于字典,in 运算符仅检查键是否存在,而不检查值。
in 运算符的时间复杂度取决于序列的类型。例如,在列表中查找元素的时间复杂度为 O(n),而在集合或字典中查找键的时间复杂度为 O(1)(平均情况下)。
in 运算符是一个非常方便的工具,用于在序列中快速检查元素的存在性。
发布于:内蒙古自治区