Python中map函數

來源:互聯網
上載者:User

標籤:資料   一個   ret   tom   列表   print   轉換函式   for   python2   

1.簡介

python 提供內建函數map(), 接收兩個參數,一個是函數,一個是序列,
map將傳入的函數依次作用到序列的每個元素,並把結果作為新的list返
回。
例如:

(1)對於list [1, 2, 3, 4, 5, 6, 7, 8, 9]
如果希望把list的每個元素都作平方,就可以用map()函數:
因此,我們只需要傳入函數f(x)=x*x,就可以利用map()函數完成這個計算:

def f(x):    return x * xprint(list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])))

輸出結果:
[1, 4, 9, 10, 25, 36, 49, 64, 81]

也可以結合lambda這樣寫:

print map(lambda x: x**2, list)

注意:map()函數不改變原有的 list,而是返回一個新的 list。

(2)list中字串轉換成int

list2 = [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]print(list(map(lambda x:int (x), list2)))

輸出結果:

[1, 2, 3, 4, 5]

利用map()函數,可以把一個 list 轉換為另一個 list,只需要傳入轉換函式。
由於list包含的元素可以是任何類型,因此,map() 不僅僅可以處理只包含數值的 list,事實上它可以處理包含任意類型的 list,只要傳入的函數f可以處理這種資料類型。

2.注意(Python3中map函數的問題):

在Python2中map函數會返回一個list列表,如代碼:

>>> def f(x, y): return (x, y)  >>> l1 = [ 0, 1, 2, 3, 4, 5, 6 ]  >>> l2 = [ ‘Sun‘, ‘Mon‘, ‘Tue‘, ‘Wed‘, ‘Thu‘, ‘Fri‘, ‘Sat‘ ] 

返回結果如下:

>>> map(f, l1, l2)  [(0, ‘Sun‘), (1, ‘Mon‘), (2, ‘Tue‘), (3, ‘Wed‘), (4, ‘Thu‘), (5, ‘Fri‘), (6, ‘Sat‘)]

 但是,在Python3中返回結果如下:

>>> map(f1, l1, l2)  <map object at 0x00000000021DA860>  

 如果想要得到Python2的那種結果,即返回list列表,那麼必須用list作用於map,如下:

>>> list(map(f1, l1, l2))  [(0, ‘Sun‘), (1, ‘Mon‘), (2, ‘Tue‘), (3, ‘Wed‘), (4, ‘Thu‘), (5, ‘Fri‘), (6, ‘Sat‘)] 
 3.例子(Python3實現):

假設使用者輸入的英文名字不規範,沒有按照首字母大寫,後續字母小寫規則,請利用map()函數,把一個list(包含若干不規範的英文名字)變成一個包含規範英文名字的list:
方法1:

def format_name(str):    str1 = str[0:1].upper() + str[1:].lower()    return str1name_list = [‘BOB‘, ‘tom‘, ‘IVy‘]print(list(map(format_name, name_list)))

方法2:

def format_name1(str):    str1 = str.capitalize()    return str1name_list = [‘BOB‘, ‘tom‘, ‘IVy‘]print(list(map(format_name1, name_list)))

方法3:

def format_name1(str):    str1 = str.title()    return str1name_list = [‘BOB‘, ‘tom‘, ‘IVy‘]print(list(map(format_name1, name_list)))

 

輸出結果:

[‘Bob‘, ‘Tom‘, ‘Ivy‘]

 

Python中map函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.