一叔扼、map和reduce:
map()函數(shù)接收兩個(gè)參數(shù)事哭,一個(gè)是函數(shù),一個(gè)是Iterable瓜富,map將傳入的函數(shù)依次作用到序列的每個(gè)元素鳍咱,并把結(jié)果作為新的Iterator返回。
list_x = [1, 2, 3, 4]
list_y = [1, 2, 3]
r = map(lambda x, y: x * x + y, list_x, list_y)
print(list(r))
寫(xiě)個(gè)簡(jiǎn)單的應(yīng)用場(chǎng)景与柑,把用戶(hù)輸入的不規(guī)范的英文名字谤辜,變?yōu)槭鬃帜复髮?xiě)蓄坏,其他小寫(xiě)的規(guī)范名字。
def lower_to_upper(s):
loop = 0
l = ""
for x in s:
if x.islower() and loop == 0:
l = l + x.upper()
loop += 1
elif x.isupper() and loop == 0:
l = l + x
loop += 1
elif x.lower() and loop != 0:
l = l + x
loop += 1
else:
l += x.lower()
return l
result = list(map(lower_to_upper, ["adam", "LISA", "barT"]))
print(result)
reduce(function, iterable[, initializer])把函數(shù)從左到右累積作用在元素上丑念,產(chǎn)生一個(gè)數(shù)值涡戳。如reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])就是計(jì)算((((1+2)+3)+4)+5)。
Python提供的sum()函數(shù)可以接受一個(gè)list并求和渠欺,現(xiàn)實(shí)現(xiàn)一個(gè)prod()函數(shù)妹蔽,可以接受一個(gè)list并利用reduce()求積。
def prod(list):
def multiply(x, y):
return x * y
return reduce(multiply, list)
print prod([1, 3, 5, 7])
未完待續(xù)~~~