Python中的map函數


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

既然已經有內置的函數了,我們就不要再去造一個輪子了。。。以前不知道這個函數,自己寫了不少額外的輪子,想起來真的很汗顏。。。

看來還是要多多學些。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM