在Python程序中查找列表中的元素总和
在本文中,我们将学习下面给出的问题陈述的解决方案。
问题陈述 -我们得到了一个可迭代的列表,我们需要计算列表的总和
在这里,我们将讨论以下三种方法
使用for循环
示例
# sum
total = 0
# creating a list
list1 = [11, 22,33,44,55,66]
# iterating over the list
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total)输出结果
Sum of the array is 231
使用while循环
示例
# Python program to find sum of elements in list
total = 0
ele = 0
# creating a list
list1 = [11,22,33,44,55,66]
# iterating using loop
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
# printing total value
print("Sum of all elements in given list: ", total)输出结果
Sum of the array is 231
通过创建函数使用递归
示例
# list
list1 = [11,22,33,44,55,66]
# function following recursion
def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
# main
total = sumOfList(list1, len(list1))
print("Sum of all elements in given list: ", total)输出结果
Sum of the array is 231
结论
在本文中,我们学习了如何打印列表中元素的总和。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短