close
現在要來看一下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 with None items. If function is None, 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.
  •  
  • 簡單的來說,就是定義一個function。接著用這個function來對一個iterable 的物件內每一個元素做處理,
  • 光看文字可能還是很難懂,直接看例子吧~!!
 
我們可以輕易地使用map來對list裡面每一個元素的資料型態做轉換,
原本有一個資料型態為字串(str)的listA , 只要設定map函式第一個參數int ,第二個參數為要轉換的list
意思就是將list裡面的每一個元素都轉型成整數(int)
>>> listA = ['1','2','3']
>>> print map(int,listA)
[1, 2, 3]
 
當然,也可以自訂函式來做各種不一樣的運算
例如定義一個multiple2的函式,透過map我們就能夠對list每一個元素做 '乘2'
其實map這個函式的功能也能夠用list comprehensive 來達成。(第8行)
>>> def multiple2(x):
... return x*2
...
>>> list1 = [1,3,5,7,9]
>>> print map(multiple2,list1)
[2, 6, 10, 14, 18]
>>>
>>> print [multiple2(x) for x in list1]
[2, 6, 10, 14, 18]
 
map也可以同時接收多個list做處裡
下面宣告三組list,一個三個參數的函式 adder(x,y,z),加總後回傳。
理所當然的,也能夠使用list comprehensive來完成。(第11行)
>>> def adder(x,y,z):
... return x+y+z
...
>>> list1 = [1,3,5,7,9]
>>> list2 = [2,4,6,8,10]
>>> list3 = [100,100,100,100,100]
>>>
>>> print map(adder,list1,list2,list3)
[103, 107, 111, 115, 119]
>>>
>>> print [adder(x,y,z) for x,y,z in zip(list1,list2,list3)]
[103, 107, 111, 115, 119]
arrow
arrow
    文章標籤
    python map() 教學
    全站熱搜

    Chris 發表在 痞客邦 留言(1) 人氣()