本站改版新增arduino频道
计算列表元素之和
定义一个数字列表,并计算列表元素之和。
例如: 输入 : [12, 15, 3, 10] 输出 : 40
实例 1
total = 0
list1 = [11, 5, 17, 18, 23]
for ele in range(0, len(list1)):
total = total + list1[ele]
print("列表元素之和为: ", total)
以上实例输出结果为:
列表元素之和为: 74
实例 2: 使用 while() 循环
total = 0
ele = 0
list1 = [11, 5, 17, 18, 23]
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
print("列表元素之和为: ", total)
以上实例输出结果为:
列表元素之和为: 74
实例 3: 使用递归
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使用 reduce 函数:
from functools import reduce
list1 = [11, 5, 17, 18, 23]
sum=reduce(lambda x,y:x+y,list1)
print(sum)
参考:
# 直接用 sum 函数求解
list1 = [11, 5, 17, 18, 23]
print("列表元素之和为: ", sum(list1))
Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号
执行时间: 0.0096940994262695 seconds