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

来源:互联网 发布:苹果ps软件 编辑:程序博客网 时间:2024/04/30 02:20

filter()-过滤序列

  1. 参数:函数
  2. 序列

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

取奇数序列

示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# Python filter 用法# 是否为奇数def isOdd(x):    return (x % 2) != 0def 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']
原创粉丝点击