Python学习十四:filter()

Python 中内置了filter()函数用于过滤序列。
使用方法:
filter()接收一个函数和一个序列。

filter()把传入的函数依次作用于每一个元素,然后依据返回值是True还是False决定保留还是丢弃该元素。

demo:
1、在一个list中。删掉偶数。仅仅保留奇数:

#filter odd number in the list
def is_odd(n):
    return n % 2 == 1

print filter(is_odd , [1 , 2 , 3 , 4 , 5 , 6 , 9 , 10 , 16])

2、把一个序列中的空字符串删掉:

#filter not_empty string in a list

def not_empty(s):
    return s and s.strip()

print filter(not_empty , ['A' , '' , 'B' , None , 'C''   '])

学习教程:
1、廖雪峰 Python教程

原文地址:https://www.cnblogs.com/gcczhongduan/p/5234069.html