一、in運算符
in運算符是Python中的一種成員運算符,用來檢查一個元素是否在另一個序列中。該運算符接受兩個參數,第一個參數是待查找的元素,第二個參數是序列。
# 列表中檢查元素是否存在 fruits = ['apple', 'banana', 'cherry'] print('apple' in fruits) # True print('orange' in fruits) # False # 字元串中檢查子串是否存在 s = 'hello world' print('world' in s) # True print('python' in s) # False # 元組中檢查元素是否存在 t = ('apple', 'banana', 'cherry') print('apple' in t) # True print('pear' in t) # False
可以看到,in運算符能夠用於不同類型的序列中,包括但不限於列表、字元串、元組等等。對於列表和元組,in運算符是基於元素的,而對於字元串則是基於子串的。
二、not in運算符
not in運算符與in相反,用於檢查一個元素是否不在另一個序列中。
# 列表中檢查元素是否不存在 fruits = ['apple', 'banana', 'cherry'] print('pear' not in fruits) # True print('apple' not in fruits) # False # 字元串中檢查子串是否不存在 s = 'hello world' print('python' not in s) # True print('world' not in s) # False # 元組中檢查元素是否不存在 t = ('apple', 'banana', 'cherry') print('pear' not in t) # True print('apple' not in t) # False
與in運算符類似,not in運算符也可以用於不同類型的序列。
三、注意事項
在使用in或not in運算符時,需要注意以下幾點:
- 如果待查找的數據不在序列中,則in運算符返回False,not in運算符返回True。
- 如果待查找的數據在序列中,則in運算符返回True,not in運算符返回False。
- 對於字元串的檢查,in運算符可以檢查一個子串是否為另一個字元串的子串,而not in則是檢查一個子串是否不是另一個字元串的子串。
- 在對字典進行成員運算時,in和not in運算符會默認判斷鍵是否存在,而不是值。
- 對於集合數據類型,in和not in運算符默認判斷的是元素是否存在。
四、總結
總的來說,in和not in運算符用於判斷一個數據項是否在一個序列中,其返回值為True或False。應用於不同類型的序列中時,其功能也略有不同。在使用時需注意區分數據類型和檢查的方式,以免出錯。
原創文章,作者:HCFH,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/142991.html