Python求一個數字列表的元素總和
阿新 • • 發佈:2020-08-19
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: 5total += 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)
程式碼貼得亂,為了給自己複習的時候可以集中精神。