python列表元素之和_python实现计算列表元素之和
目標:定義一個數字列表,并計算列表元素之和。
例如: 輸入 : [12, 15, 3, 10] 輸出 : 40
方法一:total = 0
list1 = [11, 5, 17, 18, 23]
for ele in range(0, len(list1)):
total = total + list1[ele]
print("列表元素之和為: ", total)
結果:列表元素之和為: 74
方法二:使用while()循環total = 0
ele = 0
list1 = [11, 5, 17, 18, 23]
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
print("列表元素之和為: ", total)
以上實例輸出結果為:列表元素之和為: 74
方法三:使用遞歸list1 = [11, 5, 17, 18, 23]
def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
total = sumOfList(list1, len(list1))
print("列表元素之和為: ", total)
結果:列表元素之和為: 74
以上就是python實現計算列表元素之和的詳細內容,更多請關注隨便開發網其它相關文章!
總結
以上是生活随笔為你收集整理的python列表元素之和_python实现计算列表元素之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android四周阴影效果_帮助独立开发
- 下一篇: python的变量名有哪些_【pytho