Python3-筆記-C-004-函數-map、filter、reduce & lambda

來源:互聯網
上載者:User

標籤:pytho   sof   cto   列表   ble   計算   傳回值   function   int   

f = lambda x, y, z: x + y + z
print(f(1, 2, 3)) # 6
g = lambda x, y=2, z=3: x + y + z
print(g(1, z=4, y=5)) # 10

# lambda運算式常用來編寫跳轉表(jump table),就是行為的列表或字典
L = [(lambda x: x**2),
(lambda x: x**3),
(lambda x: x**4)]
print(L[0](2),L[1](2),L[2](2)) # 4 8 16

D = {‘f1‘:(lambda: 2+3),
‘f2‘:(lambda: 2*3),
‘f3‘:(lambda: 2**3)}
print(D[‘f1‘](),D[‘f2‘](),D[‘f3‘]()) # 5 6 8

# map(function, sequence[, sequence, ...]) -> list
# 將函數調用映射到每個序列的對應元素上並返回一個含有所有傳回值的列表
def inc(x, y):
return (x, y)
la = [1, 2, 3, 4]
lb = [‘Sun‘, ‘M‘, ‘T‘, ‘W‘, ‘T‘, ‘F‘, ‘S‘]
l1 = list(map(inc, la, lb)) # <class ‘list‘>: [(1, ‘Sun‘), (2, ‘M‘), (3, ‘T‘), (4, ‘W‘)]
l2 = list(map((lambda x, y: x * y), la, la)) # 兩個參數的 <class ‘list‘>: [1, 4, 9, 16]
l3 = list(map((lambda x: x**2), la)) # 使用lambda形式 <class ‘list‘>: [1, 4, 9, 16]
l4 = list(x**2 for x in range(1, 5)) #這樣更快 <class ‘list‘>: [1, 4, 9, 16]
l5 = list(x+y for x in range(5) if x%2 == 0 for y in range(10) if y%2 ==1)
# <class ‘list‘>: [1, 3, 5, 7, 9, 3, 5, 7, 9, 11, 5, 7, 9, 11, 13]

# filter(function or None, sequence) -> list, tuple, or string
# 為已知的序列的每個元素調用給定的布爾函數,調用中,傳回值為非零的元素將被添加至一個列表中
def fun1(x):
if x > 100:
return True
else:
return False
f1 = list(filter(fun1, [2, 101, 600, 3])) # <class ‘list‘>: [101, 600]
f2 = list(filter(lambda x: x % 2 == 0, la)) # <class ‘list‘>: [2, 4]
f3 = list(filter(lambda x: True if (x > ‘a‘) else False, [‘a‘, ‘b‘, ‘c‘])) # <class ‘list‘>: [‘b‘, ‘c‘]

# reduce(function, sequence[, initial]) -> value
# (概括:把結果繼續和序列的下一個元素做累積計算)
# function參數是一個有兩個參數的函數,reduce依次從sequence中取一個元素,
# 和上一次調用function的結果做參數再次調用function。第一次調用function時,
# 如果提供initial參數,會以sequence中的第一個元素和initial作為參數調用function,
# 否則會以序列sequence中的前兩個元素做參數調用function。
from functools import reduce
c = reduce(lambda x, y: x + y, la) # 10
c = reduce(lambda x, y: x + y, la, 100) # 110

Python3-筆記-C-004-函數-map、filter、reduce & lambda

聯繫我們

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