>> 'jb51.net' in ['jb51.net/codes']
False
>>> 'jb51.net' in ('jb51.net/codes')
True # !!! 驚人結果
Python 語法規定:
(expr) 只是分組運算式,不是元組。(expr,)。因此 ('jb51.net/codes') 等價於字串 'jb51.net/codes'。in 對字串執行時為子字串搜尋,而非元素成員檢查。
| 寫法 | 型別 | 'jb51.net' in ... | 說明 |
|---|---|---|---|
['jb51.net/codes'] | list | False | 列表元素比對 |
('jb51.net/codes',) | tuple | False | 元組元素比對 (正確) |
('jb51.net/codes') | str | True | 字串子序列搜尋 (陷阱!) |
{'jb51.net/codes'} | set | False | 集合元素比對 |
('single',)。{'a', 'b', 'c'} 查找 O(1),列表/元組 O(n)。ALLOWED: set[str] = {'a', 'b'} 讓靜態分析器發現錯誤。in \( 模式,確認括號內有逗號。in 運算子的多型行為# 字串 -> 子字串搜尋
'abc' in 'xyzabc' # True
# 列表/元組/集合/字典鍵 -> 成員檢查
1 in [1, 2, 3] # True
1 in (1, 2, 3) # True
1 in {1, 2, 3} # True
'a' in {'a': 1, 'b': 2} # True (檢查鍵)
# 自訂類別支援 __contains__
class Container:
def __init__(self, items):
self.items = set(items)
def __contains__(self, x):
return x in self.items
c = Container([1,2,3])
print(2 in c) # True
Python 的 in 語意取決於右側物件型別。單元素元組缺少逗號會退化為括號運算式,導致字串被誤判為容器。養成「單元素加逗號」習慣,並善用集合進行高效率成員檢查。