2018年12月13日 函数5

filter 函数

def filter_test(func,n):
    n_s=[]
    for i in n:
        if not func:
            n_s.append(i)
    return n_s

print(filter_test(lambda x:x.endswith("sb"),l_s))

 

movie_people=['sb_a','sb_b','sxj','sb_c','sb_d']

res=filter(lambda n : not n.endswith('sb'),movie_people)
print(list(res))#判断操作 注意可以用not取非

res=map(lambda x:not x.endswith("sb"),movie_people)
print(list(res)#映射操作

 

 

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

语法

以下是 filter() 方法的语法:

filter(function, iterable)

参数

  • function -- 判断函数。
  • iterable -- 可迭代对象。

返回值

返回一个迭代器对象

-------------------------------------

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

 

reduce函数

描述

reduce() 函数会对参数序列中元素进行累积。

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

语法

reduce() 函数语法:

reduce(function, iterable[, initializer])

参数

  • function -- 函数,有两个参数
  • iterable -- 可迭代对象
  • initializer -- 可选,初始参数

返回值

返回函数计算结果。

num_l=[2,5,4]
def reduce_test(func,array,init=None):#设置init做默认参数为基数
    if init is None:
        res=array.pop(0)#注意此处用法,取第一个值,但是又删除第一个值
    else:
        res=init
    for num in array:#将列表中的每一个值做func操作,并累计循环计算
        res=func(res,num)
    return res

print(reduce_test(lambda x,y:x*y,num_l))


num_l2=[2,5,4]
from functools import reduce#从functools模块中倒入reduce
print(reduce(lambda x,y:x+y,num_l2,100))

posted @ 2018-12-13 19:30  小圣庄  阅读(96)  评论(0编辑  收藏  举报