過濾為短路檢查

filter(python 3.x)和 ifilter(python 2.x)返回一個生成器,以便在建立像 orand 這樣的短路測試時非常方便:

Python 2.x >= 2.0.1

 # not recommended in real use but keeps the example short:
from itertools import ifilter as filter

Python 2.x >= 2.6.1

 from future_builtins import filter

要查詢小於 100 的第一個元素:

car_shop = [('Toyota', 1000), ('rectangular tire', 80), ('Porsche', 5000)]
def find_something_smaller_than(name_value_tuple):
    print('Check {0}, {1}$'.format(*name_value_tuple)
    return name_value_tuple[1] < 100
next(filter(find_something_smaller_than, car_shop))
# Print: Check Toyota, 1000$
#        Check rectangular tire, 80$
# Out: ('rectangular tire', 80)

next 函式給出了下一個(在這種情況下是第一個)元素,因此它是短路的原因。