网站首页 > 基础教程 正文
Python内置函数map(), reduce()和filter()都是非常实用的函数式编程工具。
- map()函数
map()函数用于将一个函数应用于一个可迭代对象(如列表、元组等)的每个元素,并返回一个包含应用函数后的结果的迭代器。它的语法如下:
python
map(function, iterable[, iteraboe])
其中,function是用于应用函数的对象,iterable是可迭代对象,而iterable是可选的,表示要应用函数的第二个可迭代对象。下面是一个示例:
python
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # [1, 4, 9, 16, 25]
- reduce()函数
reduce()函数用于对一个可迭代对象中的元素进行累积计算,它的语法如下:
python
reduce(function, iterable[, initializer])
其中,function是用于计算累积值的函数,iterable是可迭代对象,而initializer是可选的,表示初始值。下面是一个示例:
python
from functools import reduce
import operator
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(operator.add, numbers)
print(sum_of_numbers) # 15
- filter()函数
filter()函数用于过滤可迭代对象中的元素,只保留符合条件的元素,它的语法如下:
python
filter(function, iterable)
其中,function是用于判断元素是否符合条件的函数,iterable是可迭代对象。下面是一个示例:
python
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # [2, 4]
猜你喜欢
- 2024-11-02 Python函数式编程之map/reduce/filter进阶
- 2024-11-02 Python中map函数的奇淫技巧:优化你的编程体验
- 2024-11-02 Python 内置函数与匿名函数 python匿名内部类
- 2024-11-02 第八篇:Python中函数介绍 python中的各种函数
- 2024-11-02 「每天3分钟学Python」Python中的 Map 和 Reduce
- 2024-11-02 Python中starmap有什么用的? python中start用法
- 2024-11-02 详解Python中的map、lambda和apply用法
- 2024-11-02 Python编程技巧:如何用Map, Filter, Reduce代替For循环?
- 2024-11-02 python lambda函数与map()、filter()、reduce()函数用法
- 2024-11-02 Python 函数式编程——map、reduce、filter及lambda匿名函数介绍
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)