搜索元素
Python 中的所有内置集合都实现了使用 in
检查元素成员资格的方法。
名单
alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5 in alist # True
10 in alist # False
元组
atuple = ('0', '1', '2', '3', '4')
4 in atuple # False
'4' in atuple # True
字符串
astring = 'i am a string'
'a' in astring # True
'am' in astring # True
'I' in astring # False
组
aset = {(10, 10), (20, 20), (30, 30)}
(10, 10) in aset # True
10 in aset # False
快译通
dict
有点特别:普通的 in
只检查按键。如果要搜索值,则需要指定它。如果要搜索键值对,则相同。
adict = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
1 in adict # True - implicitly searches in keys
'a' in adict # False
2 in adict.keys() # True - explicitly searches in keys
'a' in adict.values() # True - explicitly searches in values
(0, 'a') in adict.items() # True - explicitly searches key/value pairs