map函数的用法

map函数在python2和python3中稍有不同,python2直接返回一个列表,python3则返回一个map的可迭代对象


一、python2的官方解释:

map(...)
    map(function, sequence[, sequence, ...]) -> list
    
    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).

语法:

第一个参数为函数,第二个参数为可迭代对象

map(function, iterable)

实践:

1. str函数


map函数接收的第一个参数为str函数,将对象转换为字符串,第二个参数为一个列表

列表中的元素依次被str函数处理,然后添加到一个新的列表中,最后返回一个新列表

2. lambda表达式



二、python3的官方解释

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.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

用法与python2并不二致,只是返回对象不同

实践:


可以看到在python3中返回的是一个map对象,由于内部封装了__iter__方法和__next__方法,所以是可迭代对象,可以使用next()函数不断获取其中的值


参考:

http://www.runoob.com/python/python-func-map.html

阅读更多
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭