日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python教程之成員和身份運算符的用法詳解_python

作者:海擁 ? 更新時間: 2022-11-12 編程語言

成員運算符

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

原文鏈接:https://juejin.cn/post/7145486202659930126

欄目分類
最近更新