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

3 投票
5 回答
45301 浏览
提问于 2025-04-17 13:53

我有一个下面定义的函数,它可以打印出列表中的每个整数,而且运行得很好。现在我想创建一个第二个函数,这个函数可以调用或者重复使用 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

5 个回答

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

撰写回答