map函數的語法如下:
map(function, iterable, ...)
其主要作用,就是對迭代對象中每一個元素,利用function函數做一次運算,然后然后將返回結果為了一個新的可迭代對象。自己也可以寫這樣一個map函數。
1 def fun(x): 2 return x * x 3 def another_map(l): 4 for i in l: 5 yield fun(i) 6 7 input = [1, 2, 3] 8 9 print('-'*20 + 'another map defined by me' +'-'*20 ) 10 output = another_map(input) 11 print(output) 12 for x in output: 13 print(x) 14 15 print('-'*20 + 'map function' +'-'*20 ) 16 for x in map(fun, input): 17 print(x)
對應的輸出結果如下:
1 --------------------another map defined by me-------------------- 2 <generator object another_map at 0x0000000004EAA360> 3 1 4 4 5 9 6 --------------------map function-------------------- 7 1 8 4 9 9
既然已經有內置的函數了,我們就不要再去造一個輪子了。。。以前不知道這個函數,自己寫了不少額外的輪子,想起來真的很汗顏。。。
看來還是要多多學些。