Python教程

python内置函数之filter

本文主要是介绍python内置函数之filter,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、Python内建的filter()函数用于过滤序列,根据以下描述可以得知filter()函数需传入两个参数:分别为 函数(返回值类型为bool型,python中非0的数字也为True)和可迭代数据 ;返回的是一个filter对象(满足函数中判断条件为True的元素)

  filter(function or None, iterable) --> filter object

案列一(列表):

存在列表data = [-1, 2, 3, -4, 5],要求过滤掉列表中的负数,得到一个列表为:[2, 3, 5];在该案例中使用三种方式实现:普通for循环、列表生成式、内置函数filter()

'''
    1、使用普通for循环实现
'''
def demo1():
    data=[-1, 2, 3, -4, 5]
    res = []
    for i in data:
        if i>=0:
            res.append(i)
    print(res)  # 结果为[2, 3, 5]

'''
    2、使用列表推导式实现
'''
def demo2():
    data = [-1, 2, 3, -4, 5]
    res = [x for x in data if x >= 0]
    print(res)  # 结果为 [2, 3, 5]

'''
    3、使用filter 内置函数实现
'''
def demo3():
    data = [-1, 2, 3, -4, 5]
    res = list(filter(lambda x: x>=0 , data)) #这里使用到了匿名函数 lambda
    print(res)  # 结果为 [2, 3, 5]

案例二(字典):

存在一个学生成绩字典,根据学生成绩过滤出成绩大于90分的学生字典信息;使用三种方式实现:普通for循环、列表生成式、内置函数filter()

import random

'''
 1、使用普通for循环实现
'''
def demo1(score_dict):
    res = {}
    for key, value in score_dict.items():
        if value >= 90:
            res[key] = value
    print(res)

'''
 2、使用字典推导式实现
'''
def demo2(score_dict):
    res = {key: value for key, value in score_dict.items() if value >= 90}
    print(res)

'''
 3、使用内置函数filter()实现
'''
def demo3(score_dict):
    res = dict(filter(lambda x: x[1]>=90, score_dict.items()))
    print(res)    

score_dict = {f'student{i+1}' : random.randint(60,100) for i in range(10)}
print(score_dict)
demo1(score_dict)
demo2(score_dict)
demo3(score_dict)

案例三(集合):

存在集合data = {-1, -2, 3, -4, 5},要求过滤掉列表中的正数,得到一个列表为:{-1, -2, -4};在该案例中使用三种方式实现:普通for循环、集合生成式、内置函数filter()

'''
    1、使用普通for循环实现
'''
def demo1(data):
    res = set()
    for x in data:
        if x < 0:
            res.add(x)
    print(res)

'''
    2、使用集合推导式实现
'''
def demo2(data):
    res = {x for x in data if x < 0}
    print(res)

'''
    3、使用内置函数filter实现
'''
def demo3(data):
    res = set(filter(lambda x: x<0, data))
    print(res)

data = {-1, -2, 3, -4, 5}
demo1(data)
demo2(data)
demo3(data)

 

这篇关于python内置函数之filter的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!