1

我在下面定义了一个函数,可以打印列表中的每个整数,并且效果很好。我想做的是创建第二个函数,该函数将调用或重新利用该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
4

4 回答 4

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
于 2013-01-28T04:04:34.360 回答
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
于 2013-01-28T04:19:52.300 回答
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
于 2017-03-18T11:17:03.887 回答
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)


    
于 2021-12-19T07:16:16.483 回答