美文网首页
python学习-filter()函数

python学习-filter()函数

作者: Cookie_hunter | 来源:发表于2018-03-16 08:03 被阅读0次

filter()函数

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

filter()函数对于序列中的元素进行筛选,最终获取符合条件的序列
map()类似,fliter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值的Ture还是False决定保留还是丢弃该元素。

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

def a(x):
    return x % 2 == 1

b = list(filter(a,[1,2,3,4,5,6,7,8,9]))
print (b)

#结果:[1, 3, 5, 7, 9]

把一个序列中的空字符串删掉,可以这么写:

def not_empty(s):
    return s and s.strip()            #理解一下

list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))
# 结果: ['A', 'B', 'C']

相关文章

  • 学习python的第三篇

    今天学习了python的高级函数filter,sorted 学习地址:廖雪峰的官方网站filter函数:filte...

  • filter函数有点意思

    filter函数 filter(function, iterable)filter函数是python中的高阶函数,...

  • python lambda

    lambda是匿名函数。前面我们提到python高阶函数,学习了map,reduce,filter等python内...

  • 【Python】-014-函数-函数式编程-2

    python内置高阶函数 Filter函数filter(function, sequence) -> list, ...

  • 【python】第四周filter

    filter Python内建的filter()函数用于过滤序列。map()类似,filter()也接收一个函数和...

  • python

    python小工具 filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个...

  • python学习-filter()函数

    filter()函数 Python内建的filter()函数用于过滤序列 在一个list中,删掉偶数,只保留奇数,...

  • Python实用教程系列——推导式和Lambda表达式

    上次推文我们一起学习了python中的高级函数——Python实用教程系列——高阶函数Map、Filter、Red...

  • filter

    filter: Python内建的filter()函数用于过滤序列。 filter()和map()类似 filte...

  • Python高阶函数_map/reduce/filter

    本篇将开始介绍python高阶函数map/reduce/filter的用法,更多内容请参考:Python学习指南 ...

网友评论

      本文标题:python学习-filter()函数

      本文链接:https://www.haomeiwen.com/subject/debifftx.html