zoukankan      html  css  js  c++  java
  • python计算列表元素和与乘积

    python计算列表元素和与乘积

    列表之和计算

    使用sum函数

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    print(sum(numbers))
    
    使用reduce函数
    # 方式1
    from functools import reduce
    
    
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    results = reduce(lambda x, y: x + y, numbers)
    print(results)
    
    # 方式2
    from operator import add
    from functools import reduce
    
    
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    results = reduce(add, numbers)
    print(results)
    
    使用for循环
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    result = 0
    for number in numbers:
        result += number
    print(result)
    
    
    使用递归
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    def cal(list1, size):
        if size:
            return list1[size - 1] + cal(list1, size - 1)
        return size
    
    print(cal(numbers, len(numbers)))
    

    列表乘积计算

    使用for循环
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    result = 1
    for number in numbers:
        result *= number
    print(result)
    
    使用reduce函数
    # 方式1
    from functools import reduce
    
    
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    results = reduce(lambda x, y: x * y, numbers)
    print(results)
    
    # 方式2
    from operator import mul
    from functools import reduce
    
    
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    results = reduce(mul, numbers)
    print(results)
    
    使用递归函数
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    def cal(list1, size):
        if size == 0:
            return 1
        return list1[size - 1] * cal(list1, size - 1)
    
    print(cal(numbers, len(numbers)))
    
  • 相关阅读:
    第二次冲刺阶段第四天
    第二次冲刺阶段第三天
    第二次冲刺阶段第二天
    人月神话阅读笔记03
    第二次冲刺阶段第一天
    学习进度条(十二)
    课堂练习-找水王
    学习进度条(十一)
    学习进度表第十周
    构建之法阅读笔记06
  • 原文地址:https://www.cnblogs.com/wxhou/p/14113774.html
Copyright © 2011-2022 走看看