[python]map 是什麼?

  • 18590
  • 0

[python]map 是什麼?

這是一個說明文。

在 python 的內建函式裡,有一個 map 的函式。
map 不是地圖,若是照執行的意義來解釋,就是映射,白話一點就是一對一對應。

怎說?來看一下官方的說明:

map(function, iterable, ...)

Apply function to every item of iterable and return a list of 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. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

http://docs.python.org/library/functions.html#map

第一句就是定義,「執行 function,把每一個在 iterable 裡的元素當做參數,把每一個結果裝在一個 list 裡,然後回傳。可以假想,map 是長這樣的一個函數(假設 function 只需一個參數):

def map( function_point, iterable):
    result = []
    for i in iterable:
        r = function_point( i )
        result.append( r )
    return result

這種運算常發生嗎?你仔細想想,每當你的任何一段程式是長成這樣(用 c 來舉例):

for ( int i = 0; i < 100; i++)
{
    do_function( i );
}

就可以改寫成:

map( do_function, [0,1,2,…99])

do_function 是本來就要準備的,而 map 是 python 幫你準備好的(其他語言若沒有,則可以自己寫)。帶來的好處有什麼?

  1. 寫法標準化
  2. 縮短程式碼

除此之外,google 告訴你,

可以分散運算!

只要 do_function 執行時,只要傳入引數有關,map 是可以平行運算的。也就是 map 不一定非得像上面所寫從 0 跑到 99,只要你有能力改進 map 這個程式,分散到各台電腦上跑,執行完的結果都會一樣。(http://research.google.com/archive/mapreduce.html)
在 python 裡就有一個現成的多process 的 map 可用。 (multiprocessing.Pool 的 map。http://docs.python.org/library/multiprocessing.html?highlight=multiprocess#multiprocessing.pool.multiprocessing.Pool.map)

Google 還告訴你,他們的系統就是多採用 MapReduce 的 programming model 才能應付如此大量的資料,分散到各電腦上運算又保證結果正確。MapReduce 算不上是 framework,而叫 programming model。如果把 framework 叫做戰略,那 map/reduce 就叫戰術。因為小到每一個程式的每個段落都可能會出現可數迴圈,只要是可數迴圈,不論是否需要結果都可使用這種寫程式的風格。而這種風格在 functional programming 非常常見。大家可以先不知道 functional programming,但 map 好用就應該要常用。

雖然說,python 是 functional language 所以用 map 很自然。
但是其他語言也不是辦不到。
c/c++ 語言,就用 function pointer 來指定 function。
c#, vb .Net 可以用 delegate 來處理。
偷懶一點,參數用 object,嚴格一點,用 template 指定 type。

試試,loop 換成 map 吧!

關於更詳細的 map / reduce 說明及範例,請參閱以下連結
http://code.google.com/edu/parallel/mapreduce-tutorial.html

 

 

 

分享