网站首页 > 基础教程 正文
map()方便可迭代对象各个元素之间进行操作。
Python内置函数 map()
1. 语法 map(function, iterable, ...)
二个参数,都为必选:
- function 功能函数,可以是None,起个占位符作用,使语法保持正确
- iterable 可迭代对象,可以是一个也可以是多个
- 返回一个迭代器,其中包含iterable中每一个元素经过function后的内容。
- 如果iterable有多个,则function中应该包含多个元素,如果多个iterable中的长度不一样,则终止于最短的一个元素。
In [1]:
map(None, range(9))
Out[1]:
<map at 0x33b09b0>
In [2]:
list1 = [1, 3, 5]
In [3]:
def plus_one(_): return _ + 1
In [4]:
map(plus_one, list1)
Out[4]:
<map at 0x33b09d0>
In [5]:
tuple(map(plus_one, list1))
Out[5]:
(2, 4, 6)
In [6]:
list(map(plus_one, [2, 4, 6]))
Out[6]:
[3, 5, 7]
In [7]:
list2 = [4, 5, 6, 7]
In [8]:
def plusab(a,b): return a + b
In [9]:
list(map(plusab, list1, list2))
Out[9]:
[5, 8, 11]
2. 与匿名函数lambda一起使用
map()与lambda一起用最方便快捷
In [10]:
list(map(lambda x: x ** 3, [1, 2, 3]))
Out[10]:
[1, 8, 27]
In [11]:
list(map(lambda a, b: a + b, ['a', 'b', 'c'], ['我', '爱','你']))
Out[11]:
['a我', 'b爱', 'c你']
In [12]:
list(map(lambda x, y: x * y, [1, 2, 3], [4, 5, 6]))
Out[12]:
[4, 10, 18]
猜你喜欢
- 2024-11-02 Python函数式编程之map/reduce/filter进阶
- 2024-11-02 Python中map函数的奇淫技巧:优化你的编程体验
- 2024-11-02 python内置函数map/reduce/filter
- 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()函数用法
- 最近发表
- 标签列表
-
- 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)