您的位置:首页 > 编程语言 > Python开发

Python学习十四:filter()

2016-03-02 10:59 495 查看
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教程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: