Python中map()內建函數淺析

MapReduce的設計靈感來自於函數式編程,這裏不打算提MapReduce,就拿python中的map()函數來學習一下。

文檔中的介紹在這裏:

map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterablearguments 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 withNoneitems. If function isNone, 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.

一點一點看:

1、對可迭代函數'iterable'中的每一個元素應用‘function’方法,將結果作爲list返回。

來個例子:

1 >>> def add100(x):
2 ...     return x+100
3 ...
4 >>> hh = [11,22,33]
5 >>> map(add100,hh)
6 [111122133]
就像文檔中說的:對hh中的元素做了add100,返回了結果的list。

2、如果給出了額外的可迭代參數,則對每個可迭代參數中的元素‘並行’的應用‘function’。(翻譯的不好,這裏的關鍵是‘並行’)

1 >>> def abc(a, b, c):
2 ...     return a*10000 + b*100 + c
3 ...
4 >>> list1 = [11,22,33]
5 >>> list2 = [44,55,66]
6 >>> list3 = [77,88,99]
7 >>> map(abc,list1,list2,list3)
8 [114477225588336699]
看到並行的效果了吧!在每個list中,取出了下標相同的元素,執行了abc()。
3、如果'function'給出的是‘None’,自動假定一個‘identity’函數(這個‘identity’不知道怎麼解釋,看例子吧
1 >>> list1 = [11,22,33]
2 >>> map(None,list1)
3 [112233]
4 >>> list1 = [11,22,33]
5 >>> list2 = [44,55,66]
6 >>> list3 = [77,88,99]
7 >>> map(None,list1,list2,list3)
8 [(114477), (225588), (336699)]
用語言解釋好像有點拗口 ,例子應該很容易理解。

介紹到這裏應該差不多了吧!不過還有東西可以挖掘:

stackoverflow上有人說可以這樣理解map():

1 map(f, iterable)
2  
3 基本上等於:
4  
5 [f(x) for in iterable]
趕快試一下:
1 >>> def add100(x):
2 ...     return + 100
3 ...
4 >>> list1 = [11,22,33]
5 >>> map(add100,list1)
6 [101102103]
7  
8 >>> [add100(i) for in list1]
9 [101102103]
哦,輸出結果一樣。原來map()就是列表推導式啊!要是這樣想就錯了:這裏只是表面現象!再來個例子看看:
1 >>> def abc(a, b, c):
2 ...     return a*10000 + b*100 + c
3 ...
4 >>> list1 = [11,22,33]
5 >>> list2 = [44,55,66]
6 >>> list3 = [77,88,99]
7 >>> map(abc,list1,list2,list3)
8 [114477225588336699]
這個例子我們在上面看過了,若是用列表推導應該怎麼寫呢?我想是這樣的:
1 [abc(a,b,c) for in list1 for in list2 for in list3]

但是看到結果,發現根本不是這麼回事:

1 [114477114488114499115577115588115599116677116688116699224477224488224499225577225588225599226677226688226699334477334488334499335577335588335599336677336688336699]
這便是上面列表推導的結果。怎麼會這麼多?當然了列表推導可以這麼寫:
1 result = []
2  
3 for in list1:
4     for in list2:
5         for in list3:
6             result.append(abc(abc))
原來如此,若是將三個list看做矩陣的話:
11
22
33
44
55
66
77
88
99

map()只做了列上面的運算,而列表推導(也就是嵌套for循環)做了笛卡爾乘積。

 ACM有時需要要a b c這樣的一行格式輸入,這時可以用map函數來處理,這裏假設a,b,c都是整數。

a, b, c = map(int, raw_input().split())

 raw_input函數輸入的是字符串,字符串的split方法用來將字符串分割成序列。

OK,就寫到這裏。僅個人理解,如有差錯請指正,多謝!

上面的例子有些來自於這裏:

http://infohost.nmt.edu/tcc/help/pubs/python/web/map-function.html

http://stackoverflow.com/questions/10973766/understanding-the-map-function-python

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章