广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python教程之成员和身份运算符的用法详解
  • 776
分享到

Python教程之成员和身份运算符的用法详解

2024-04-02 19:04:59 776人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录成员运算符in 运算符'not in' 运算符身份运算符'is' 运算符'is not' 运算符成员运算符 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成员 身份运算符内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python教程之成员和身份运算符的用法详解

本文链接: https://www.lsjlt.com/news/120496.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作