python计算列表元素与乘积详情

作者:Python热爱者 时间:2023-05-12 00:50:19 

插入代码块

使用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)))

来源:https://blog.csdn.net/qdPython/article/details/126017314

标签:python,计算,列表,元素,乘积
0
投稿

猜你喜欢

  • php微信公众号开发(4)php实现自定义关键字回复

    2024-04-28 09:45:33
  • SQL语句(T-SQL汇总) 用T-SQL画出这些图形

    2024-01-13 15:24:35
  • python2和python3在处理字符串上的区别详解

    2021-10-07 03:29:31
  • Azkaban3.81.x部署过程及遇到的坑

    2022-10-24 21:38:22
  • chatGPT deBug解决管理员登入服务器返回401问题

    2022-08-07 06:38:09
  • oracle初始化参数设置

    2010-07-31 12:47:00
  • PHP chunk_split()函数讲解

    2023-06-09 13:54:44
  • 如何利用pygame实现简单的五子棋游戏

    2023-04-12 17:48:03
  • Python namedtuple命名元组实现过程解析

    2022-08-20 14:27:20
  • Centos 7.9安装MySQL8.0.32的详细教程

    2024-01-26 02:22:32
  • windows中python实现自动化部署

    2023-06-24 16:04:14
  • ThinkPHP中自定义错误页面和提示页面实例

    2024-05-02 17:16:21
  • php mail to 配置详解

    2024-05-13 09:22:51
  • selenium+python自动化测试之页面元素定位

    2021-09-30 18:08:55
  • Python使用multiprocessing创建进程的方法

    2022-08-03 14:09:21
  • Javascript基础教程之比较操作符

    2024-04-10 16:15:05
  • 为Python的Tornado框架配置使用Jinja2模板引擎的方法

    2022-07-19 03:49:07
  • uniqueidentifier转换成varchar数据类型的sql语句

    2011-09-30 11:17:48
  • Python计算图片数据集的均值方差示例详解

    2023-02-26 15:55:38
  • Pandas实现自定义Excel格式并导出多个sheet表

    2022-10-04 18:46:34
  • asp之家 网络编程 m.aspxhome.com