python filter函数(40)

目录

一.filter函数简介

二.filter函数使用

1.filter函数简单使用

2.filter函数配合匿名函数Lambda使用

 


一.filter函数简介

filter函数主要用来筛选数据,过滤掉不符合条件的元素,并返回一个迭代器对象,如果要转换为列表list或者元祖tuple,可以使用内置函数list() 或者内置函数tuple()来转换;

filter函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中,就好比是用筛子,筛选指定的元素;

python filter函数(40)_第1张图片

 

语法:

filter(function, iterable)

参数:

function – 函数名;

iterable – 序列或者可迭代对象;

返回值:通过function过滤后,将返回True的元素保存在迭代器对象中,最后返回这个迭代器对象(python2.0x版本是直接返回列表list);

 

python filter函数(40)_第2张图片

 

二.filter函数使用

1.filter函数简单使用

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:何以解忧
@Blog(个人博客地址): shuopython.com
@WeChat Official Account(微信公众号):猿说python
@Github:www.github.com

@File:python_process_Pool.py
@Time:2020/1/14 21:25

@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!
"""


def check(i):
    # 如果是偶数返回 True 否则返回False
    return True if i%2 == 0 else False

if __name__ == "__main__":

    list1 =[1,2,3,4,5,6]
    result = filter(check,list1)
    print(result)
    print(type(result))

    # 将返回的迭代器转为列表list或者元组
    print(list(result))
    print(type(list(result)))

输出结果:



[2, 4, 6]

 

 

2.filter函数配合匿名函数Lambda使用

def check_score(score):
    if score > 60:
        return  True
    else:
        return False

if __name__ == "__main__":

    # 成绩列表
    student_score = {"zhangsan":98,"lisi":58,"wangwu":67,"laowang":99,"xiaoxia":57}

    # 筛选成绩大于60的成绩列表
    result = filter(lambda score:score > 60,student_score.values())
    # 与上面一行代码等价
    # result = filter(check_score, student_score.values())

    print(result)
    print(type(result))

    # 将返回的迭代器转为列表list或者元组
    print(list(result))
    print(type(list(result)))

输出结果:



[98, 67, 99]

注意:filter函数返回的是一个迭代器对象,往往在使用时需要先将其转换为列表list或者元祖tuple之后再操作;

python filter函数其实和内置函数map()使用方法类似,map()函数也是将迭代器或者序列中的每一个元素映射到指定的函数中,操作完成之后再返回修改后的迭代器对象;

 

猜你喜欢:

1.python匿名函数lambda

2.python map函数

3.python 函数不定长参数*argc,**kargcs

 

转载请注明:猿说Python » python filter函数

 

                                                                          技术交流、商务合作请直接联系博主

                                                                                     扫码或搜索:猿说python

python教程公众号

                                                                                        猿说python

                                                                              微信公众号 扫一扫关注

你可能感兴趣的:(python技术杂谈,python,filter函数,python,filter,filter函数,python教程,猿说python)