目标:定义一个数字列表,并计算列表元素之和。
例如: 输入 : [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 = 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实现计算列表元素之和的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号