社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python3中一些高阶函数map、reduce、filter详解及示例

若数 • 4 年前 • 353 次点击  
阅读 45

Python3中一些高阶函数map、reduce、filter详解及示例

在编程语言中,高阶函数指的是接受函数作为输入或输出的函数。

map概述

  python中的map()函数是一个内置的高阶函数,一般用法是map(function, iterable)。需要传入一个函数,这个函数可以是内置的,也可以是自己定义,也可以是匿名函数即lambda。第二个参数是一个可迭代对象,如列表、字典字符串等。map函数返回的是一个map对象,也是一个可迭代对象,可以利用for循环迭代查看元素,也可以尝试list()将其转为列表对象操作,map形式: map(function, iterable, ...)

map用法

1.计算列表中所有数的平方

L1 = [1, 2, 3, 4]


# 计算某数的平方
def square(x):
    return x ** 2


square_result = map(square, L1)
print(list(square_result))

# 配合lambda最佳
square_result = map(lambda x: x ** 2, L1)
print(list(square_result))
复制代码

示例结果:

[1, 4, 9, 16]
[1, 4, 9, 16]
复制代码

2. 处理序列对象中的字符串

# 集中处理字符串开头和结尾的换行符和空格
S = [
    'I like Python\r',
    '\t\n      Python make me happy \n',
    ' without python, without living.'
]

NEW_S = list(map(lambda s: s.strip(), S))
print(NEW_S)
# 当然此例利用列表解析更加简洁:
NEW_S = [s.strip() for s in S]
print(NEW_S)
复制代码

示例结果:

['I like Python', 'Python make me happy', 'without python, without living.']
['I like Python', 'Python make me happy', 'without python, without living.']
复制代码

多参数传递

map也接受多个可迭代对象作为参数传递,若可迭代对象元素数量不一致则传递至元素数量最小的为止

# 两组数两两相加
L1 = [1, 2, 3, 4, 5, 6, 7]
L2 = [5, 4, 3, 2, 1]
sum_result = map(lambda x, y: x + y, L1, L2)
for one in sum_result:
    print(one)
复制代码

示例结果:

6
6
6
6
6
复制代码

reduce概述

reduce用于对可迭代对象中的元素进行累积操作,reduce接受两个参数,一个是函数f(x, y)参数(该函数必须有两个参数),另一个是可迭代对象。reduce行为是先将可迭代对象的前两个元素传入f(x, y)中,然后不断将f(x, y)的返回值再次和下一个迭代对象传入f(x, y),直到迭代完迭代对象中的元素,并返回最终的f(x, y)的返回值。reduce形式: reduce(function, iterable[, initializer])

reduce用法

在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在 functools 模块里,如果想要使用它,则需要通过引入 functools 模块来调用 reduce() 函数。

from functools import reduce
L = [1,2,3,4,5]
sum_results = reduce(lambda x,y: x + y, L) 
print(sum_results)
复制代码

示例结果:

15
复制代码

上例即我们通过reduce高阶函数完成了对列表中五个数的累加过程。

filter概述

filter用于过滤筛选可迭代对象中的元素,如果符合条件则返回对应的元素序列(类型为filter),filter接受两个参数,一个是函数用于筛选元素,返回值为TrueFlase,另一个是可迭代对象。

filter用法

evens = filter(is_odd, range(-5, 10))
print(list(evens))
复制代码

示例结果:

[2, 4, 6, 8]
复制代码
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/33161
 
353 次点击