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: \n\t", 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: \n\t", 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: \n\t", 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)

代碼貼得亂,為了給自己復習的時候可以集中精神。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM