函數式編程->reduce

"""# 需求:把list裏面的數字加起來num_l = [1, 2, 3, 4, 5, 100]res = 0for num in num_l:    res += num# print(res)# 定義函數num_l = [1, 2, 3, 4, 5, 100]def reduce_test(array):    res = 0    for num in array:        res += num    return(res)print(reduce_test(num_l))# 邏輯仍然是寫死了,全部的值乘起來呢?"""# 另外一種升級num_l = [1, 2, 3, 4, 5, 100]def multi(m,n):    return m * ndef reduce_test(func, array, init=None):    # res = 1 這麼寫又寫死了.    if init is None:        res = array.pop(0)    else:        res = init    for i in array:        res = func(res, i)    return resprint(reduce_test(multi, num_l))print(reduce_test(lambda m,n:m*n, num_l))print(reduce_test(multi, num_l, 100))# 升級:reduce, 功能:把一個完整的序列進行處理,最終獲得一個值.from functools import reducenum_l = [1, 2, 3, 4, 5, 100]print(reduce(lambda m,n:m*n, num_l))
相關文章
相關標籤/搜索