Applyfunctionto every item ofiterableand return a list of the results. If additionaliterablearguments are passed,functionmust 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. IffunctionisNone, 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). Theiterablearguments may be a sequence or any iterable object; the result is always a list.
一點一點看:
1、對可迭代函數(shù)'iterable'中的每一個元素應用‘function’方法涮阔,將結果作為list返回吃型。
來個例子:
>>> def add100(x):
...? ? return x+100
...
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]
就像文檔中說的:對hh中的元素做了add100,返回了結果的list。
2悦陋、如果給出了額外的可迭代參數(shù),則對每個可迭代參數(shù)中的元素‘并行’的應用‘function’服傍。(翻譯的不好吹零,這里的關鍵是‘并行’)
>>> 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]
看到并行的效果了吧!在每個list中,取出了下標相同的元素伸辟,執(zhí)行了abc()。
3静稻、如果'function'給出的是‘None’振湾,自動假定一個‘identity’函數(shù)(這個‘identity’不知道怎么解釋押搪,看例子吧)
>>> 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():
map(f, iterable)
基本上等于:
[f(x) for x in iterable]
趕快試一下:
>>> 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]
哦,輸出結果一樣躯畴。原來map()就是列表推導式啊嚷缭!要是這樣想就錯了:這里只是表面現(xiàn)象!再來個例子看看:
>>> 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]
這個例子我們在上面看過了,若是用列表推導應該怎么寫呢百侧?我想是這樣的:
[abc(a,b,c) for a in list1 for b in list2 for c in list3]
但是看到結果,發(fā)現(xiàn)根本不是這么回事:
[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]
這便是上面列表推導的結果辛润。怎么會這么多灵迫?當然了列表推導可以這么寫:
result = []
for a in list1:
for b in list2:
for c in list3:
result.append(abc(abc))
原來如此瀑粥,若是將三個list看做矩陣的話:
112233
445566
778899
map()只做了列上面的運算,而列表推導(也就是嵌套for循環(huán))做了笛卡爾乘積修噪。
OK,就寫到這里脏款。僅個人理解,如有差錯請指正,多謝痒谴!
上面的例子有些來自于這里:
http://infohost.nmt.edu/tcc/help/pubs/python/web/map-function.html
http://stackoverflow.com/questions/10973766/understanding-the-map-function-python
原網(wǎng)頁地址:https://my.oschina.net/zyzzy/blog/115096#0-youdao-...