Python中map()函式淺析
http://my.oschina.net/zyzzy/blog/115096
MapReduce的設計靈感來自於函數語言程式設計,這裡不打算提MapReduce,就拿python中的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 withNone
一點一點看:
1、對可迭代函式'iterable'中的每一個元素應用‘function’方法,將結果作為list返回。
來個例子:
?1 2 3 4 5 6 |
>>> def
add100(x):
... return
x + 100
...
>>> hh =
[ 11 , 22 , 33 ]
>>> map (add100,hh)
[ 111 ,
122 , 133 ]
|
2、如果給出了額外的可迭代引數,則對每個可迭代引數中的元素‘並行’的應用‘function’。(翻譯的不好,這裡的關鍵是‘並行’)
1 2 3 4 5 6 7 8 |
>>> def
abc(a, b, c):
... return
a * 10000
+ b * 100
+ c
...
>>> list1
= [ 11 , 22 , 33 ]
>>> list2
= [ 44 , 55 , 66 ]
>>> list3
= [ 77 , 88 , 99 ]
>>> map (abc,list1,list2,list3)
[ 114477 ,
225588 ,
336699 ]
|
3、如果'function'給出的是‘None’,自動假定一個‘identity’函式(這個‘identity’不知道怎麼解釋,看例子吧)
?1 2 3 4 5 6 7 8 |
>>> list1
= [ 11 , 22 , 33 ]
>>> map ( None ,list1)
[ 11 ,
22 , 33 ]
>>> list1
= [ 11 , 22 , 33 ]
>>> list2
= [ 44 , 55 , 66 ]
>>> list3
= [ 77 , 88 , 99 ]
>>> map ( None ,list1,list2,list3)
[( 11 ,
44 , 77 ), ( 22 ,
55 , 88 ), ( 33 ,
66 , 99 )]
|
介紹到這裡應該差不多了吧!不過還有東西可以挖掘:
stackoverflow上有人說可以這樣理解map():
?1 2 3 4 5 |
map (f, iterable)
基本上等於:
[f(x) for
x in
iterable]
|
1 2 3 4 5 6 7 8 9 |
>>> def
add100(x):
... return
x +
100
...
>>> list1
= [ 11 , 22 , 33 ]
>>> map (add100,list1)
[ 101 ,
102 , 103 ]
>>> [add100(i)
for i in
list1]
[ 101 ,
102 , 103 ]
|
1 2 3 4 5 6 7 8 |
>>> def
abc(a, b, c):
... return
a * 10000
+ b * 100
+ c
...
>>> list1
= [ 11 , 22 , 33 ]
>>> list2
= [ 44 , 55 , 66 ]
>>> list3
= [ 77 , 88 , 99 ]
>>> map (abc,list1,list2,list3)
[ 114477 ,
225588 ,
336699 ]
|
1 |
[abc(a,b,c)
for a in
list1 for
b in list2
for c in
list3]
|
但是看到結果,發現根本不是這麼回事:
?1 |
[ 114477 ,
114488 ,
114499 , 115577 ,
115588 ,
115599 , 116677 ,
116688 ,
116699 , 224477 ,
224488 ,
224499 , 225577 ,
225588 ,
225599 , 226677 ,
226688 ,
226699 , 334477 ,
334488 ,
334499 , 335577 ,
335588 ,
335599 , 336677 ,
336688 ,
336699 ]
|
1 2 3 4 5 6 |
result =
[]
for
a in list1:
for
b in
list2:
for
c in
list3:
result.append(abc(abc))
|
11 | 22 | 33 |
44 | 55 | 66 |
77 | 88 | 99 |
map()只做了列上面的運算,而列表推導(也就是巢狀for迴圈)做了笛卡爾乘積。
OK,就寫到這裡。僅個人理解,如有差錯請指正,多謝!
上面的例子有些來自於這裡:
http://infohost.nmt.edu/tcc/help/pubs/python/web/map-function.html
http://stackoverflow.com/questions/10973766/understanding-the-map-function-python