filter(python 3.x)和ifilter(python 2.x)返回一个生成器,因此在创建短路测试如or或时它们可以非常方便and:
# 不建议实际使用,但使示例简短: from itertools import ifilter as filter
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))
# 打印:检查丰田,1000美元
# 方格花纹轮胎,80 $
# 出:('矩形轮胎',80)所述next-function给出的下一个(在这种情况下第一)元件,因此也就是为什么它的短路的原因。