zoukankan      html  css  js  c++  java
  • 函数式编程->reduce


    """
    # 需求:把list里面的数字加起来
    num_l = [1, 2, 3, 4, 5, 100]
    res = 0
    for 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 * n
    def 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 res
    print(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 reduce
    num_l = [1, 2, 3, 4, 5, 100]
    print(reduce(lambda m,n:m*n, num_l))
  • 相关阅读:
    error :expected initializer before
    数字转字符
    转载转载转载指针占几个字节
    转载转载转载
    二维数组1
    响应式布局
    flex布局
    wepy踩坑经历
    css命名规范(转载)
    28.设计模式
  • 原文地址:https://www.cnblogs.com/Windows-phone/p/9729986.html
Copyright © 2011-2022 走看看