1. 程式人生 > >Python中巢狀for迴圈的一個問題

Python中巢狀for迴圈的一個問題

這個序列處理中的很基礎但又很重要的問題,比如說, 從第一個列表中找第二個列表中存在的項

items = [(1,2), 3, "book", 3.14]
tests = [100, (1,2)]

通常做法

>>> items = [(1,2), 3, "book", 3.14]
>>> tests = [100, (1,2)]
>>> for key in tests:                       # 先遍歷第二個列表
...     for item in items:                  # 再遍歷第一個列表
...         if key == item:                 # 做出條件判斷
...             print(key, "WAS FOUND!")
...             break                       # 找到終止小迴圈
...     else:                               # 未找到處理方式
...         print(key, "NOT FOUND!")
...
100 NOT FOUND!
(1, 2) WAS FOUND!
>>>

改用in運算子來測試成員關係

>>> items = [(1,2), 3, "book", 3.14]
>>> tests = [100, (1,2)]
>>> for key in tests:
...     if key in items:
...         print(key, "WAS FOUND!")
...     else:
...         print(key, "NOT FOUND!")
...
100 NOT FOUND!
(1, 2) WAS FOUND!
>>>

備註: 從簡潔度和效能及程式碼結構來考慮,第二種方式,無疑要好的多。