不使用sum()函数,打印一个整数列表的总和

3
我有一个下方定义的函数,它打印列表中的每个整数,它可以很好地工作。我想做的是创建第二个函数,调用或重用 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

1
我很困惑。int_list 的参数中带有 self,但是没有用到它,反而迭代了一个从未提及的名为 grades 的东西。此外,它将 grades 中的每个元素加到 上,这与在每次迭代中只将 index 设置为 n 是一样的。所以我很迷茫。我感觉 int_list 函数是你真正问题的干扰项。 - kojiro
这是一个简单的例子,说明如何实现 http://www.evaluzio.net/doc/d6475eaf58664b3f9342 - Elalfer
5个回答

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

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

这个问题是否也可以用lambda语句来解决?这似乎是它的完美应用场景。 - ApproachingDarknessFish
@ValekHalfHeart 当然,有很多更好的方法来做这件事。如果sum不存在,我会写成reduce(int.__add__, alist)。不过这只是学术上的讨论,因为sum才是正确的方法,而且我们被要求不使用它。不过,对于这个答案,我想说明正在发生的事情,所以我认为写出函数会更清晰明了。 - kojiro
@SnakesandCoffee 当然可以!但正如我爷爷常说的那样,“为什么要进口,当你可以在这里得到你所需要的呢?” - kojiro

0
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)


    

如果你想知道为什么你的答案没有被点赞,那就加上一些关于你代码如何工作的解释。 - jcoppens

0
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

0
你可以使用 functools 模块中的 reduce 函数。
from functools import module

s=reduce(lambda x,y:x+y, integer_list)

输出

225

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接