[英]Print the sum of a list of integers without using sum()
我在下面定义了一个函数,可以打印列表中的每个整数,并且效果很好。 我想做的是创建第二个函数,该函数将调用或重新利用int_list()
函数来显示已生成列表的总和。
我不确定这是否是由代码本身固有地执行的——我对 Python 语法相当陌生。
integer_list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
def int_list(self):
for n in integer_list
index = 0
index += n
print index
在您的代码中,您在每个循环中设置index=0
,因此它应该在for
循环之前初始化:
def int_list(grades): #list is passed to the function
summ = 0
for n in grades:
summ += n
print summ
输出:
int_list([5, 10, 15, 20, 25, 30, 35, 40, 45])
5
15
30
50
75
105
140
180
225
要获得整数列表的总和,您有几个选择。 显然最简单的方法是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
integer_list = [5, 10, 15, 20, 25, 30, 35, 40, 45] #this is your list
x=0 #in python count start with 0
for y in integer_list: #use for loop to get count
x+=y #start to count 5 to 45
print (x) #sum of the list
print ((x)/(len(integer_list))) #average
list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
#counter
count = 0
total = 0
for number in list:
count += 1
total += number
#don'n need indent
print(total)
print(count)
# average
average = total / count
print(average)
您可以使用 functools 模块中的 reduce 函数
from functools import module
s=reduce(lambda x,y:x+y, integer_list)
输出
225
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.