要获得整数列表的总和,您有几个选择。显然最简单的方法是sum
,但我想你想学习如何自己做。另一种方法是在加起来时存储总和:
def sumlist(alist):
"""Get the sum of a list of numbers."""
total = 0 # start with zero
for val in alist: # iterate over each value in the list
# (ignore the indices – you don't need 'em)
total += val # add val to the running total
return total # when you've exhausted the list, return the grand total
第三个选项是reduce
,它是一个函数,它本身接受一个函数并将其应用于运行总计和每个连续参数。
def add(x,y):
"""Return the sum of x and y. (Actually this does the same thing as int.__add__)"""
print '--> %d + %d =>' % (x,y) # Illustrate what reduce is actually doing.
return x + y
total = reduce(add, [0,2,4,6,8,10,12])
--> 0 + 2 =>
--> 2 + 4 =>
--> 6 + 6 =>
--> 12 + 8 =>
--> 20 + 10 =>
--> 30 + 12 =>
print total
42