Python成員運算子測試給定值是否為序列中的成員,例如字串,列表或元組。Python中有兩個成員運算子,如下所述 -
運算子 | 描述 | 範例 |
---|---|---|
in |
如果在指定的序列中找到一個變數的值,則返回true ,否則返回false 。 |
- |
not in |
如果在指定序列中找不到變數的值,則返回true ,否則返回false 。 |
- |
假設變數a
的值為True
,變數b
的值為False
,參考以下程式碼實現 -
#!/usr/bin/python3
#coding=utf-8
#save file: membership_operators_example.py
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
將上面程式碼儲存到檔案: membership_operators_example.py 中,執行結果如下 -
F:\worksp\python>python membership_operators_example.py
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list