搜尋元素

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