Python教程之成員和身份運算符的用法詳解
成員運算符
Python 提供了兩個成員運算符來檢查或驗證值的成員資格。它測試序列中的成員資格,例如字符串、列表或元組。
in 運算符
'in' 運算符用于檢查序列中是否存在字符/子字符串/元素。如果在序列中找到指定元素,則評估為 True,否則為 False。例如,
'G' in 'GeeksforGeeks' # 檢查字符串中的“G”
True
'g' in 'GeeksforGeeks' # 檢查字符串中的“g”,因為 Python 區(qū)分大小寫,返回 False
False
'Geeks' in ['Geeks', 'For','Geeks'] # 檢查字符串列表中的“Geeks”
True
10 in [10000,1000,100,10] # 檢查整數(shù)列表中的 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 程序
# 定義一個接受兩個列表的函數(shù)()
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")
復(fù)制代碼輸出:
x is NOT present in given list
y is present in given list
身份運算符
如果兩個對象實際上具有相同的數(shù)據(jù)類型并共享相同的內(nèi)存位置,則使用標(biāo)識運算符來比較對象。
有不同的身份運算符,例如
'is' 運算符
如果運算符兩側(cè)的變量指向同一對象,則計算結(jié)果為 True,否則計算結(jié)果為 false。
# Python程序說明'is'恒等運算符的使用 x = 5 y = 5 print(x is y) id(x) id(y)
輸出:
True
140704586672032
140704586672032
在給定的示例中,變量 x 和 y 都分配了值 5,并且都共享相同的內(nèi)存位置,這就是返回 True 的原因。
'is not' 運算符
如果運算符兩側(cè)的變量指向不同的對象,則計算結(jié)果為 false,否則計算結(jié)果為 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
到此這篇關(guān)于Python教程之成員和身份運算符的用法詳解的文章就介紹到這了,更多相關(guān)Python成員 身份運算符內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 使用poster模塊進行http方式的文件傳輸?shù)椒?wù)器的方法
今天小編就為大家分享一篇python 使用poster模塊進行http方式的文件傳輸?shù)椒?wù)器的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
Python基于socket模塊實現(xiàn)UDP通信功能示例
這篇文章主要介紹了Python基于socket模塊實現(xiàn)UDP通信功能,結(jié)合實例形式分析了Python使用socket模塊實現(xiàn)IPV4協(xié)議下的UDP通信客戶端與服務(wù)器端相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
基于Python實現(xiàn)批量讀取大量nc格式文件并導(dǎo)出全部時間信息
這篇文章主要為大家詳細介紹了如何基于Python語言,逐一讀取大量.nc格式的多時相柵格文件并導(dǎo)出其中所具有的全部時間信息的方法,需要的可以參考下2024-01-01

