Python的map()方法如何使用?

Python的map()方法如何使用?

>>> help(map)
Help on class map in module builtins:
 
class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.

从上面可以得到的信息是:

  • map()返回的是一个map对象(python2.0中返回的是列表,后面会讲到)。
  • map的第二个参数是可变的,iterables等同于args,*iterables代表可变的并且可迭代的对象。
  • 当有多个迭代参数对象,同时,迭代对象内的元素个数又不一致时,以最短的那个迭代对象作为停止的标准。

作用:会根据提供的函数对指定序列做映射。

map函数语法:

map(fun,*iterable)
fun	函数
*iterable	一个或者多个序列(取决于函数的参数)

返回值:

python2.0 返回的是列表

python3.0 返回的是迭代器,必要时需要遍历得到结果

map()函数返回的是一个新的对象,不会改变原有对象。

如下代码是在python3.0的交互式模式下运行的:

>>> def sum(a,b):
...     return a+b
...
>>> obj = map(sum,[1,2,3,4],[1,2,3])   # 传入2个序列,序列内的元素个数不一致,以最短的序列为停止的标准
>>> obj 
<map object at 0x000001CD44CF5518>   # 返回的是迭代器
>>> for i in obj:    # 遍历迭代器
...     print(i)
...
2
4
6
>>> obj = map(lambda x,y:x+y,[1,2,3,4],[1,2,3,4])   # 使用lambda匿名函数
>>> obj
<map object at 0x000001CD44E18860>
>>> for i in obj:
...     print(i)
...
2
4
6
8
>>>
posted @ 2023-06-15 15:34  布衣梦蝶1978  阅读(40)  评论(0编辑  收藏  举报