python->filter

来源:互联网 发布:石油大亨mac版 编辑:程序博客网 时间:2024/06/11 22:48

1 filter()函数用于过滤序列,filter函数把传入的每个函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃元素

ex:

def is_odd(n):    return n % 2 == 1list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))# 结果: [1, 5, 9, 15]

把一个序列中的空字符串删掉,可以这么写:

def not_empty(s):    return s and s.strip()list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))# 结果: ['A', 'B', 'C']

原创粉丝点击