1. 程式人生 > 實用技巧 >python之高階函式(map/reduce)

python之高階函式(map/reduce)

map將傳入的函式依次作用到序列的每個元素,並把結果作為新的Iterator返回。

map()函式接收兩個引數,一個是函式,一個是Iterable

例項

# def f(x):
#     return x * x
# a=[1,2,3,4,5,6,7,8,9]
# r=map(f,a)  # 將a中的元素分別帶入到函式中
# print(list(r))

reduce把一個函式作用在一個序列[x1, x2, x3, ...]上,這個函式必須接收兩個引數

例項:求和

# from  functools import reduce
# def f(x,y):
#     return x + y
# a=[1,2,3,4,5,6,7,8,9] # r=reduce(f,a) # print(r)

reduce常用來做累計計算

將不規範的英文變為首字母大寫

# def dx(name):
#     return name.title()
# L1 = ['adam', 'LISA', 'barT']
# L2 = list(map(dx, L1))
# print(L2)

累計求積

# from  functools import reduce
# def f(x,y):
#     return x * y
# a=[1,2,3,4,5,6,7,8,9]
# r=reduce(f,a)
# print(r)

將字串轉換乘浮點數

# from  functools import reduce
# def def1(x):# 定義函式
#     digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.':'.'}#定義字典
#     return digits[x] #輸出對應的值
# p=0
# m=1
# def def2(x,y):#定義函式
#     if y=='.':
#         global p
#         p=1
#
return x # if p==0: # return x * 10 + y # else: # global m # m=m*0.1 # return x+y*m # print(reduce(def2,map(def1,'24234.32423')))