PHP前端开发

python实现计算列表元素之和

百变鹏仔 1个月前 (01-22) #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()循环

立即学习“Python免费学习笔记(深入)”;

total = 0ele = 0 list1 = [11, 5, 17, 18, 23]   while(ele <p>以上实例输出结果为:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">列表元素之和为:  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-tutorials.html" target="_blank">python教程