map函数学习

map()函数是python内置的高阶函数,作用是接收一个函数和一个可迭代对象,把可迭代对象的元素依次作用在函数上,得到一个新的可迭代对象。

多说无益看个例子:

res = map(lambda x:x**2,[1,5,7,4,8])
print(list(res)) #[1, 25, 49, 16, 64]
print(list(res)) #[]

what?当我第二次再次输出list(res)时打印的是空列表,抱着这种疑惑我查询了map()函数的源码:

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确实接收的是一个函数还有可迭代对象,但是下面的英语是什么意思呢?so easy.意思很简单就是说,创建一个迭代器,使用迭代器的每个元素完成函数的功能,当迭代器耗尽时停止。

但是这跟我第二次输出空列表有什么关系呢?思来想去,我觉得应该是这样的,第一次print(list(res))时迭代器运行到最后一个元素8了,那么第二次再次print(list(res))时迭代器从8开始位置继续运行,结果8后面什么也没有,结果就是空列表。

我靠,这样的话,那我这个list(res)只能用一次吗?这岂不是很扯吗?

可以这样做,将list(res)赋值给一个变量即可,这样每次使用使用这个变量即可。

res = map(lambda x:x**2,[1,5,7,4,8])
value= list(res)
print(value)#[1, 25, 49, 16, 64]
print(value)#[1, 25, 49, 16, 64]

 

posted @ 2019-04-14 15:55  上古战神  阅读(366)  评论(0编辑  收藏  举报