Python 第十四天 (2年归来)(函数 filter、reduce)

filter函数 : 是内置高阶函数
    作用:根据条件筛选可迭代对象里的元素,保留复核条件的内容
    语法格式:
        filter(判断函数,可迭代序列)
movie_people = [
    "陈宇", "李浩", "周凯", "吴俊", "郑阳",
    "王婷", "刘佳", "黄欣", "张琳", "徐菲"]

ret = []
for p in movie_people:
    if not p.startswith('陈'):
        ret.append(p)
print(ret)
ret1 = []
for p in movie_people:
    if p.startswith('李'):
        ret1.append(p)

print(ret1)

# 终极版本
lambda n:n.startwith('王'),movie_people
print(list(filter(lambda n:n.startswith('王'),movie_people)))

  

reduce函数:不是内置全局函数,需要从functools模块导入
    作用:对序列中的元素累计迭代计算
    语法:
        reduce(计算函数,可迭代对象,[初始值])
 
 
 
num_1 = [1,2,3,10]
res = 0
# 方法1
for i in num_1:
    res+=i
    
print(res)

# 方法2
def reduce_test(array):
    rest = 0
    for num in array:
        rest+=num
    return res
print(reduce_test(num_1))

# 所有值都乘起来
def multi(x,y):
    return x*y

lambda x,y:x*y
from functools import reduce
# 最终形式
print(reduce(lambda x,y:x*y,num_1,100))

 

posted @ 2026-07-22 16:24  贫道财迷  阅读(5)  评论(0)    收藏  举报