过滤为短路检查

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 函数给出了下一个(在这种情况下是第一个)元素,因此它是短路的原因。