python filter函数

来源:互联网 发布:新浪网的域名和ip地址 编辑:程序博客网 时间:2024/04/27 10:17

Python内建的filter()函数用于过滤序列。

例如,在一个list中,删掉偶数,只保留奇数,可以这么写:

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']