Python求一个数字列表的元素总和。练手:
第一种方法,直接sum(list):
1 lst = list(range(1,11)) #创建一个1-10的数字列表
2 total = 0 #初始化总和为0
3
4 #第一种方法
5 total = sum(lst); #直接调用sum()函数
6 print(total) #55
第二种方法,while循环:
lst = list(range(1,11)) #创建一个1-10的数字列表
total = 0 #初始化总和为0
i = 0
while(i < len(lst)):
total += lst[i]
i += 1
print(total) #输出55
#当然也可以把while循环编写在函数里
def sumOfList(alst):
total = 0
i = 0
while i < len(alst):
total += alst[i]
i += 1
return total
print("Sum is: \n\t", sumOfList(lst));
第三种方法for循环:
1 lst = list(range(1,11)) #创建一个1-10的数字列表
2 total = 0 #初始化总和为0
3
4 for i in lst:
5 total += i
6
7 print(total) #输出55
8 #也可以写成如下:
9 def sumOfList(alst):
10 total = 0
11 for i in alst:
12 total += i
13 return total
14 print("Sum is: \n\t", sumOfList(lst));
第四种方法还是for循环:
1 lst = list(range(1,11)) #创建一个1-10的数字列表
2 total = 0 #初始化总和为0
3
4 for i in range(len(lst)):
5 total += lst[i]
6 print(total) #输出55
7 #也可以写成如下这样
8 def sumOfList(alst):
9 total = 0
10 i = 0
11 for i in range(len(alst)):
12 total += alst[i]
13 return total
14 print("Sum is: \n\t", sumOfList(lst))
第五种方法reduce:
1 lst = list(range(1,11)) #创建一个1-10的数字列表
2 total = 0 #初始化总和为0
3
4 from functools import reduce
5 total = reduce(lambda x,y:x+y, lst)
6 print(total) #输出55
第六种方法递归:
1 lst = list(range(1,11)) #创建一个1-10的数字列表
2 total = 0 #初始化总和为0
3
4 def sumOfList(lst,size):
5 if (size == 0):
6 return 0
7 else:
8 return lst[size-1] + sumOfList(lst, size-1)
9
10 total = sumOfList(lst,len(lst))
11 print("Sum is: ", total)
代码贴得乱,为了给自己复习的时候可以集中精神。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章