高阶函数map和filter

1. 高阶函数

  • 内建高阶函数:map()、filter()
  • 高阶函数至少满足两个任意的一个条件
    • 能接收一个或多个函数作为输入
    • 输出一个函数

2. 高阶函数map的使用

  • map()函数:根据提供的函数处理序列中的元素、处理完后返回一个迭代器对象

  • 语法格式

    map(function,iterable,...)
    
  • 示例:

    • 示例1、使用map基本

      num = range(1,11)
      def handle(n):
      	return n * 2
      result = map(handle, num)
      print(list(result))
      
    • 示例2、或者使用匿名函数:

      num = range(1,11)
      result = map(lambda n:n * 2, num)
      print(list(result))
      

3. 高阶函数filter的使用

  • filter()函数:用于过滤序列,过滤掉不符合条件的元素,处理完后返回一个迭代器对象。

  • 语法格式:

    filter(function,iterable)
    
  • 示例:

    • 示例1、使用filter基本使用

      num = range(1,11)
      def handle(n):
      	if n % 2 == 0:
      		return n
      result = filter(handle, num)
      print(list(result))
      
    • 示例2、使用匿名函数

      num = range(1,11)
      result = filter(lambda n:n % 2 == 0, num)
      print(list(result))
      

4. 案例

4.1 案例1、高阶函数map的使用

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py


# 需求: 处理列表中每一个元素,都乘以2

def f(n):
    return n * 2

a = range(1,11)

result = map(f, a)
print(result)

for i in result:
    print(i)


# 使用匿名函数
num = range(1,11)
result = map(lambda n:n * 2, num)
print(list(result))

4.2 案例2、高阶函数filter的使用

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py


# filter的基本
a = range(1,11)
def handle(n):
    if n % 2 == 0:
        return n
result = filter(handle, a)
print(list(result))



# 使用匿名函数
num = range(1,11)
s1 = filter(lambda n:n % 2 == 0, num)
print(list(s1))
posted @ 2023-01-06 10:06  七月流星雨  阅读(34)  评论(0编辑  收藏  举报