Python 成员运算符

pythonserver side programmingprogramming

Python 的成员运算符测试序列中的成员身份,例如字符串、列表或元组。有两个成员运算符,如下所述 −

Sr.No运算符 &描述示例
1in
如果在指定序列中找到变量,则计算结果为 true,否则为 false。
x in y,如果 x 是序列 y 的成员,则此处的 in 结果为 1。
2not in
如果在指定序列中未找到变量,则计算结果为 true,否则为 false。
x not in y,如果 x 不是序列 y 的成员,则此处的 not in 结果为 1。

示例

#!/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

相关文章