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

Python基础-高阶函数-filter()

2017-12-11 14:43 441 查看

filter()-过滤序列

参数:函数

序列

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

取奇数序列

示例

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python filter 用法

# 是否为奇数
def isOdd(x):
return (x % 2) != 0

def filterTest():
# 函数,序列
result = filter(isOdd, [1, 2, 3,4,5])
print(result)

filterTest()


运行结果

D:\PythonProject>python run.py
[1, 3, 5]


删除空字符串

示例代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python filter 用法

# 删除空字符串
def whithoutEmptyString(s):
return s and s.strip()

def filterTest():
# 函数,序列
result = filter(whithoutEmptyString, ["A", "", "B"])
print(result)

filterTest()


运行结果

D:\PythonProject>python run.py
['A', 'B']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 过滤 sorted