Python成员 身份运算符

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python成员 身份运算符

海拥   2022-09-29 我要评论

成员运算符

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们