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)

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

  • 相关阅读:
    前后端分离的若依(ruoyi)基本使用
    Redis (error) NOAUTH Authentication required.解决方法
    Creating Server TCP listening socket 127.0.0.1:6379: bind: No error。。。启动遇到问题的解决办法
    持续集成
    Java compiler level does not match the version of the installed Java project facet问题解决
    控制台报错:Unknown database 'xxxxx'
    走进docker-machine
    走进docker-compose
    java新手学习路线
    Spring WebFlux 教程:如何构建反应式 Web 应用程序
  • 原文地址:https://www.cnblogs.com/mafu/p/13528414.html
Copyright © 2011-2022 走看看