不使用sum()打印整数列表的总和

时间:2013-01-28 04:02:17

标签: python list

我在下面定义了一个函数,它打印列表中的每个整数,并且它完美地运行。我想要做的是创建第二个函数,该函数将调用或重新使用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

3 个答案:

答案 0 :(得分:7)

在您的代码中,您在每个循环中设置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

答案 1 :(得分:2)

要获得整数列表的总和,您有几个选择。显然最简单的方法是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

答案 2 :(得分:0)

integer_list = [5,10,15,20,25,30,35,40,45]#这是你的清单

x = 0 #in python count以0开始

表示整数列表中的y:#use for循环来获取计数

x + = y #start计数5到45

print(x)列表的#sum

print((x)/(len(integer_list)))#graphic