函數式編程->map

# 函數式編程之map"""num_l = [1, 2, 10, 5, 3, 7]# 需求1:對每一個之執行平方# 方法1:for 循環ret = []for i in num_l:    ret.append(i**2)# 方法2:對上面的過程進行封裝def map_test(array):    ret = []    for i in array:        ret.append(i**2)    return ret# 需求2:隊列表的每一個值自增1def map_test(array):    ret = []    for i in array:        ret.append(i+1)    return ret# 需求3:隊列表的每一個值自減1def map_test(array):    ret = []    for i in array:        ret.append(i-1)    return ret# 需求N:....# 怎麼應對上面的狀況?def add_one(i):    return i + 1def reduce_one(i):    return i - 1def map_test(func, array):    ret = []    for i in array:        ret.append( func(i))    return retprint(map_test(add_one, [1, 2, 3, 4])) # 這也是一種高階函數, [2, 3, 4, 5]# add_one改寫print(map_test(lambda x:x+1, [1, 2, 3, 4])) # [2, 3, 4, 5]print(map_test(lambda x:x-1, [1, 2, 3, 4])) # [0, 1, 2, 3]# map就是map_test的功能print(map(lambda x:x+1, [1, 2, 3, 4])) # <map object at 0x102979f60>res = map(lambda x:x+1, [1, 2, 3, 4])for i in res:    print(i)# print(list(res)) 兩種輸出均可以,notes:只能迭代一次.print(list(map(lambda x:x+1, [1, 2, 3, 4])))print(list(map(add_one, [1, 2, 3, 4]))) # 實現簡單,難讀# notes, map的第二個參數是可迭代對象便可.# map的第一個參數能夠傳入函數,或者是lamda.print(list(map(lambda x:x.upper(), "supter"))) # ['S', 'U', 'P', 'T', 'E', 'R']""""""# map filtermovie_people = ["sb_alex", "sb_wupeiqi", "sb_yuanhao", "haha1", "hsha2"]ret = []for p in movie_people:    if not p.startswith("sb"):        ret.append(p)print(ret)# 函數封裝def filter_test(array):    ret = []    for p in array:        if not p.startswith("sb"):            ret.append(p)    return retprint(filter_test(movie_people))"""# 改造方式和上面同樣,最終的程序結果是movie_people = ["sb_alex", "sb_wupeiqi", "sb_yuanhao", "haha1", "hsha2"]def filter_test(func,array):    ret = []    for p in array:        if not func(p):            ret.append(p)    return retprint(filter_test(lambda n:n.startswith("sb"),movie_people)) # ['haha1', 'hsha2']# filtermovie_people = ["sb_alex", "sb_wupeiqi", "sb_yuanhao", "haha1", "hsha2"]print("filter", list(filter(lambda n:n.startswith("sb"), movie_people)))
相關文章
相關標籤/搜索