Python3 map() 函数

@[TOC](Python3 map() 函数)

1、描述

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

2、 语法

# map() 函数语法:
map(function, iterable, ...)

3、参数

# function -- 函数
# iterable -- 一个或多个序列

4、返回值

Python 2.x 返回列表。

Python 3.x 返回迭代器。

5、实例

5.1 实例1

>>>a = map(lambda x, y: x + y, [1, 2, 3], [1, 2])
>>>print(a, type(a))

<map object at 0x000000000508F688> <class 'map'>
>>>for i in a:
>>>    print(i)

2
4
>>>next(a)

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-23-15841f3f11d4> in <module>
----> 1 next(a)

StopIteration: 

5.1 实例2

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
发布了158 篇原创文章 · 获赞 7 · 访问量 9726

猜你喜欢

转载自blog.csdn.net/weixin_44983653/article/details/104818448