Python: map() and reduce()

來源:互聯網
上載者:User

標籤:英文名   bsp   tom   下標   lower   turn   輸入   col   參數   

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

舉例說明,比如我們有一個函數f(x)=x2,要把這個函數作用在一個list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()實現如下:

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

result:

[1, 4, 9, 16, 25, 36, 49, 64, 81]

reduce把一個函數作用在一個序列[x1, x2, x3...]上,這個函數必須接收兩個參數,reduce把結果繼續和序列的下一個元素做累積計算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
Practice:

【練習1】利用map()函數,把使用者輸入的不規範的英文名字,變為首字母大寫,其他小寫規範名字。輸入:[‘adam‘, ‘LISA‘, ‘barT‘],輸出:[‘Adam‘, ‘Lisa‘, ‘Bart‘]

答:

def firstToUpper(x):    s1 = x[:1].upper()    s2 = x[1:].lower()    s3 = s1 + s2    return s3
map(firstToUpper,[‘aleN‘,‘TOM‘,‘hello‘])

解釋: x[:1]: x string 的第一個字元(從 0 開始到 1 下標但是不包含1下標); x[1:]: x string 的第二個字元一直到最後, 即從下標 1 開始到最後。。。

結果:

[‘Alen‘, ‘Tom‘, ‘Hello‘]

【練習2】Python提供的sum()函數可以接受一個list並求和,請編寫一個prod()函數,可以接受一個list並利用reduce()求積。

def prod(x,y):    return x+yreduce(prod,[1,2,3,4,5,6,7,8100])

結果:

8128

 

Python: map() and reduce()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.