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决策