您现在的位置是:网站首页> 编程资料编程资料
Python教程之成员和身份运算符的用法详解_python_
2023-05-25
549人已围观
简介 Python教程之成员和身份运算符的用法详解_python_
成员运算符
Python 提供了两个成员运算符来检查或验证值的成员资格。它测试序列中的成员资格,例如字符串、列表或元组。
in 运算符
'in' 运算符用于检查序列中是否存在字符/子字符串/元素。如果在序列中找到指定元素,则评估为 True,否则为 False。例如,
'G' in 'GeeksforGeeks' # 检查字符串中的“G” True 'g' in 'GeeksforGeeks' # 检查字符串中的“g”,因为 Python 区分大小写,返回 False False 'Geeks' in ['Geeks', 'For','Geeks'] # 检查字符串列表中的“Geeks” True 10 in [10000,1000,100,10] # 检查整数列表中的 10 True dict1={1:'Geeks',2:'For',3:'Geeks'} # 检查字典键中的 3 3 in dict1 True# Python 程序说明使用“in”运算符在列表中查找常见成员 list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] for item in list1: if item in list2: print("overlapping") else: print("not overlapping") 输出
not overlapping
not overlapping
not overlapping
not overlapping
not overlapping
没有使用 in 运算符的相同示例:
# 说明在不使用“in”运算符的情况下在列表中查找常见成员的 Python 程序 # 定义一个接受两个列表的函数() def overlapping(list1, list2): c = 0 d = 0 for i in list1: c += 1 for i in list2: d += 1 for i in range(0, c): for j in range(0, d): if(list1[i] == list2[j]): return 1 return 0 list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] if(overlapping(list1, list2)): print("overlapping") else: print("not overlapping") 输出
not overlapping
'not in' 运算符
如果在指定序列中没有找到变量,则评估为 true,否则评估为 false。
# Python 程序来说明 not 'in' 运算符 x = 24 y = 20 list = [10, 20, 30, 40, 50] if (x not in list): print("x is NOT present in given list") else: print("x is present in given list") if (y in list): print("y is present in given list") else: print("y is NOT present in given list") 复制代码输出:
x is NOT present in given list
y is present in given list
身份运算符
如果两个对象实际上具有相同的数据类型并共享相同的内存位置,则使用标识运算符来比较对象。
有不同的身份运算符,例如
'is' 运算符
如果运算符两侧的变量指向同一对象,则计算结果为 True,否则计算结果为 false。
# Python程序说明'is'恒等运算符的使用 x = 5 y = 5 print(x is y) id(x) id(y)
输出:
True
140704586672032
140704586672032
在给定的示例中,变量 x 和 y 都分配了值 5,并且都共享相同的内存位置,这就是返回 True 的原因。
'is not' 运算符
如果运算符两侧的变量指向不同的对象,则计算结果为 false,否则计算结果为 true。
# Python程序说明'is not'恒等运算符的使用 x = 5 if (type(x) is not int): print("true") else: print("false") # Prints True x = 5.6 if (type(x) is not int): print("true") else: print("false")输出:
False
True
到此这篇关于Python教程之成员和身份运算符的用法详解的文章就介绍到这了,更多相关Python成员 身份运算符内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- Python深度学习之Keras模型转换成ONNX模型流程详解_python_
- Python深度学习之FastText实现文本分类详解_python_
- Python GUI程序类写法与Label介绍_python_
- 10个Python常用的损失函数及代码实现分享_python_
- Tensorflow加载模型实现图像分类识别流程详解_python_
- Python+tkinter实现音乐下载软件的制作_python_
- Python实现图像手绘效果的方法详解_python_
- python贪吃蛇核心功能实现上_python_
- 基于Python实现语音识别和语音转文字_python_
- 利用Python实现自制文件搜索小工具_python_
