Python成員運算符示例

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

上一篇: Python基本運算符 下一篇: Python決策