zoukankan      html  css  js  c++  java
  • Python求一个数字列表的元素总和

    Python求一个数字列表的元素总和。练手:

    第一种方法,直接sum(list):

    1 lst = list(range(1,11)) #创建一个1-10的数字列表
    2 total = 0 #初始化总和为0
    3 
    4 #第一种方法
    5 total = sum(lst); #直接调用sum()函数
    6 print(total) #55

    第二种方法,while循环:

    lst = list(range(1,11)) #创建一个1-10的数字列表
    total = 0 #初始化总和为0
    
    i = 0
    while(i < len(lst)):
        total += lst[i]
        i += 1
    print(total) #输出55
    #当然也可以把while循环编写在函数里
    def sumOfList(alst):
        total = 0
        i = 0
        while i < len(alst):
            total += alst[i]
            i += 1
        return total
    print("Sum is: 
    	", sumOfList(lst));

    第三种方法for循环:

     1 lst = list(range(1,11)) #创建一个1-10的数字列表
     2 total = 0 #初始化总和为0
     3 
     4 for i in lst:
     5     total += i
     6 
     7 print(total) #输出55
     8 #也可以写成如下:
     9 def sumOfList(alst):
    10     total = 0
    11     for i in alst:
    12         total += i
    13     return total
    14 print("Sum is: 
    	", sumOfList(lst));

    第四种方法还是for循环:

     1 lst = list(range(1,11)) #创建一个1-10的数字列表
     2 total = 0 #初始化总和为0
     3 
     4 for i in range(len(lst)):
     5     total += lst[i]
     6 print(total) #输出55
     7 #也可以写成如下这样
     8 def sumOfList(alst):
     9     total = 0
    10     i = 0
    11     for i in range(len(alst)):
    12         total += alst[i]
    13     return total
    14 print("Sum is: 
    	", sumOfList(lst))

    第五种方法reduce:

    1 lst = list(range(1,11)) #创建一个1-10的数字列表
    2 total = 0 #初始化总和为0
    3 
    4 from functools import reduce
    5 total = reduce(lambda x,y:x+y, lst)
    6 print(total) #输出55

    第六种方法递归:

     1 lst = list(range(1,11)) #创建一个1-10的数字列表
     2 total = 0 #初始化总和为0
     3 
     4 def sumOfList(lst,size):
     5     if (size == 0):
     6         return 0
     7     else:
     8         return lst[size-1] + sumOfList(lst, size-1)
     9 
    10 total = sumOfList(lst,len(lst))
    11 print("Sum is: ", total)

    代码贴得乱,为了给自己复习的时候可以集中精神。

  • 相关阅读:
    大数据Hadoop第二周——配置新的节点DataNode及ip地址
    vue环境搭建详细步骤
    苹果电脑Mac系统如何下载安装谷歌Chrome浏览器
    点云的基本特征和描述
    ModuleNotFoundError: No module named 'rospkg'
    ROS的多传感器时间同步机制Time Synchronizer
    Spring Cloud 2020 版本重大变革,更好的命名方式!
    Spring MVC 接收请求参数所有方式总结!
    阿里为什么不用 Zookeeper 做服务发现?
    微服务之间最佳调用方式是什么?
  • 原文地址:https://www.cnblogs.com/mafu/p/13528414.html
Copyright © 2011-2022 走看看