先看一下python2中的map函數:
def map(function, sequence, *sequence_1): # real signature unknown; restored from __doc__
"""
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).
"""
return []
也即是將一個function作用於sequence中每個元素身上,最後返回這個被function作用後的list。
再看一下python3中的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.
"""
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
在python3中map被封裝成了一個類,功能依舊是將function作用於要被遍歷的序列,但是最後返回的結果就是一個對象了。
通過代碼舉一個將int轉換爲float的例子:
if __name__ == '__main__':
x = [1, 2, 3, 4, 5]
y = map(float, x)
print(y)
python2中:
[1.0, 2.0, 3.0, 4.0, 5.0]
python3中:
<map object at 0x000001FB6DAF0A58>
如何將python3中的對象轉換爲python2中的形式呢?
只需要通過list作用於map即可:
if __name__ == '__main__':
x = [1, 2, 3, 4, 5]
y = list(map(float, x))
print(y)
[1.0, 2.0, 3.0, 4.0, 5.0]