map函數是Python里面比較重要的函數,設計靈感來自於函數式編程。Python官方文檔中是這樣解釋map函數的:
- map ( function, iterable, ... )
-
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.
即map函數接收的第一個參數為一個函數,可以為系統函數例如float、或者def定義的函數、或者lambda定義的函數均可。
舉一個簡單的例子,下面這個例子在Python2.7下是可以正常顯示的:
ls = [1,2,3] rs = map(str, ls) #打印結果 ['1', '2', '3'] lt = [1, 2, 3, 4, 5, 6] def add(num): return num + 1 rs = map(add, lt) print rs #[2,3,4,5,6,7]
但是在Python3下我們輸入:
ls=[1,2,3] rs=map(str,ls) print(rs)
顯示的卻是:
<map at 0x3fed1d0>
而不是我們想要的結果,這也是Python3下發生的一些新的變化,如果我們想得到需要的結果需要這樣寫:
ls=[1,2,3] rs=map(str,ls) print(list(rs))
這樣顯示的結果即為我們想要看到的。這一點在《機器學習實戰》的第10章中會有一點幫助。