map() 会根据提供的函数对指定序列做映射。
第一个参数function
以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
map(function, iterable, ...)
参数说明:
源码内容
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.
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
# 1.计算列表里所有元素的平方
def square(x):
return x**2
ret01 = map(square,[1,2,3])
print(ret01) #
for i in ret01:
print(i)
'''
1
4
9
'''
# 2.lambda函数实现以上功能
ret02 = map(lambda x:x**2,[1,2,3])
lst02 = [i for i in ret02] # 通过列表推导式
print(lst02) # [1, 4, 9]
# 3.参数中多个迭代器的情况
ret03 = map(lambda x,y:x+y,[1,2,3],[2,3,4])
lst03 = [item for item in ret03]
print(lst03) # [3, 5, 7]
# 3.多个迭代器中元素个数不同时
# 会从左到右,以最短为准,取完为止
ret04 = map(lambda x,y:x+y,[2,3,4],[2,3,4,5])
lst04 = [item for item in ret04]
print(lst04) # [4, 6, 8]