在Python中查找 List 的总和和平均值
给定一个列表。任务是找到列表的总和和平均值。列表的平均值定义为元素的总和除以元素的数量。
例子:
Input: [4, 5, 1, 2, 9, 7, 10, 8]
Output:
sum = 46
average = 5.75
Input: [15, 9, 55, 41, 35, 20, 62, 49]
Output:
sum = 286
average = 35.75
方法一:朴素的方法
在这种方法中,我们将遍历列表并将每个元素添加到变量 count 中,该变量存储第 i个元素的总和,然后将总和除以变量总数以找到平均值。
例子:
Python3
# Python program to find the sum
# and average of the list
L = [4, 5, 1, 2, 9, 7, 10, 8]
# variable to store the sum of
# the list
count = 0
# Finding the sum
for i in L:
count += i
# divide the total elements by
# number of elements
avg = count/len(L)
print("sum = ", count)
print("average = ", avg)
Python3
# Python program to find the sum
# and average of the list
L = [4, 5, 1, 2, 9, 7, 10, 8]
# using sum() method
count = sum(L)
# finding average
avg = count/len(L)
print("sum = ", count)
print("average = ", avg)
输出:
sum = 46
average = 5.75
方法二:使用 sum() 方法
sum() 方法返回作为其参数传递的列表的总和。然后我们将总和除以 len() 方法以找到平均值。
例子:
Python3
# Python program to find the sum
# and average of the list
L = [4, 5, 1, 2, 9, 7, 10, 8]
# using sum() method
count = sum(L)
# finding average
avg = count/len(L)
print("sum = ", count)
print("average = ", avg)
输出:
sum = 46
average = 5.75