Python 基础知识:成员运算符(in / not in)
作者:野牛程序员:2025-12-22 09:55:33python阅读 1996
Python 基础知识:成员运算符(in / not in)
# /*
# Python 基础知识:成员运算符(in / not in)
# --------------------------------------------------------
# 功能:
# 1) 展示成员运算符的基本作用
# 2) 演示其在字符串、列表、字典、集合中的典型用法
# 3) 说明成员判断在搜索与条件判断中的价值
# */
# ========================================
print("示例一:字符串中的成员判断")
text = "python"
print("'p' in text =", ('p' in text))
print("'x' in text =", ('x' in text))
print("'on' in text =", ('on' in text))
print("'py' not in text =", ('py' not in text))
print("-" * 40)
# ========================================
print("示例二:列表中的成员判断")
nums = [10, 20, 30, 40]
print("20 in 列表 =", (20 in nums))
print("99 not in 列表 =", (99 not in nums))
print("-" * 40)
# ========================================
print("示例三:字典中的成员判断(只判断键)")
info = {"name": "Tom", "age": 18}
print("'name' in 字典 =", ('name' in info))
print("'Tom' in 字典 =", ('Tom' in info)) # 值不会被判断
print("'age' not in 字典 =", ('age' not in info))
print("-" * 40)
# ========================================
print("示例四:集合中的成员判断(最快的数据结构)")
s = {1, 2, 3, 4}
print("3 in 集合 =", (3 in s))
print("9 not in 集合 =", (9 not in s))
print("-" * 40)
# ========================================
print("示例五:成员判断常用于搜索任务")
target = 23
arr = [5, 9, 23, 100]
if target in arr:
print("找到目标:", target)
else:
print("未找到目标:", target)
print("-" * 40)
# ========================================
print("示例六:成员判断结合条件语句")
password_list = ["123456", "888888", "admin"]
pwd = "admin"
if pwd in password_list:
print("密码过于简单,请更换")
# ========================================
# 要点总结:
# 1) 成员运算符 in / not in 用于判断某元素是否存在于容器中;
# 2) 字符串判断的是子串;
# 3) 列表、元组判断的是元素本身;
# 4) 字典的成员判断默认只检查键,不检查值;
# 5) 集合的成员判断速度最快,适合需要频繁查询的场景;
# 6) 成员运算符广泛用于输入校验、搜索、权限判断、过滤等逻辑中。
# */
# 示例一:字符串中的成员判断
# 'p' in text = True
# 'x' in text = False
# 'on' in text = True
# 'py' not in text = False
# ----------------------------------------
# 示例二:列表中的成员判断
# 20 in 列表 = True
# 99 not in 列表 = True
# ----------------------------------------
# 示例三:字典中的成员判断(只判断键)
# 'name' in 字典 = True
# 'Tom' in 字典 = False
# 'age' not in 字典 = False
# ----------------------------------------
# 示例四:集合中的成员判断(最快的数据结构)
# 3 in 集合 = True
# 9 not in 集合 = True
# ----------------------------------------
# 示例五:成员判断常用于搜索任务
# 找到目标: 23
# ----------------------------------------
# 示例六:成员判断结合条件语句
# 密码过于简单,请更换野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

