Python 成員運算子


Python 的成員運算子用於測試序列(如字串、列表或元組)中的成員。共有兩種成員運算子,如下所示 -

序號運算子和說明示例
1in
如果在指定的序列中找到變數,則評估結果為真;否則為假。
x in y,此處 in 結果為 1,如果 x 是序列 y 的成員。
2not in
如果在指定的序列中沒有找到變數,則評估結果為真;否則為假。
x not in y,此處 not in 結果為 1,如果 x 不是序列 y 的成員。

示例

 即時演示

#!/usr/bin/python
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"
a = 2
if ( a in list ):
   print "Line 3 - a is available in the given list"
else:
   print "Line 3 - a is not available in the given list"

輸出

執行上述程式後,會產生以下結果 -

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

更新於:2020 年 1 月 24 日

128 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.