1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| """ 和map()类似。filter也接收一个序列。区别是:filter把传入额函数依次作用于每个元素,然后根据 返回值是True 还是Flase决定保留还是丢弃该元素 """ def is_odd(n): return n % 2 == 1 print(list(filter(is_odd, [1,2,3,4,5,6,7,8,9,10,11])))
def not_empty(s): return s and s.strip()
print(list(filter(not_empty,['a', '', None, 'B', 'C', 'D']))) """返回值: ['a', 'B', 'C', 'D'] 注意到:filter函数返回的是一个lterator,也就是一个惰性序列,所以要强迫fliter完成计算结果,需要用到方法list """
|