Python函數化編程整理

來源:互聯網
上載者:User

標籤:列表   round   映射   dba   list   練習   匿名   元素   import   

1.映射函數
items=[1,2,3,4,5]def inc(x):return x+1list(map(inc,items))

[2, 3, 4, 5, 6]

>>> a = [i+1 for i in range(3)]>>> list(map((lambda x:x+5),a))
[5, 6, 7] 2.過濾函數
>>> list(filter((lambda x:x>1),a))
[2]3.規約函數:將列表所有元素依次計算後返回唯一結果累加:>>> from functools import reduce>>> reduce((lambda x,y:x+y),a)45累乘
>>> arr = [i+1 for i in range(4)]>>> reduce((lambda x,y:x*y),arr)
244.lamdba函數:匿名函數,其他列子裡有不列舉5.列表產生式
>>> a = [i+1 for i in range(3)]>>> a

[1, 2, 3]

練習:列表[1,2,3,4,5]中過濾奇數。
>>> arr = list(filter((lambda x:x%2==0),[i+1 for i in range(5)]))>>> arr
[2, 4]練習:通過兩個列表構建字典。>>> a = [i+1 for i in range(3)]>>> b = [‘a‘,‘b‘,‘c‘]>>> c = {i:j for i in a for j in b}>>> c

{0: ‘c‘, 1: ‘c‘, 2: ‘c‘}

Python函數化編程整理

聯繫我們

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