写一个 Python 程序来计算列表项的平均值。这个 Python 示例允许输入列表项,并使用 sum 函数计算总和和平均值。
avglist = []
Number = int(input("Total Number of List Items = "))
for i in range(1, Number + 1):
value = int(input("Please enter the %d List Item = " %i))
avglist.append(value)
total = sum(avglist)
avg = total / Number
print('\nThe Sum Of List Items = ', total)
print('\nThe Average Of List Items = ', avg)
在这个 python 程序中,我们从统计模块中导入了平均值,并从 functools 模块中进行了缩减。这两个 Python 函数都将计算列表项的平均值。
from statistics import mean
from functools import reduce
avglist = []
Number = int(input("Total Number of List Items = "))
for i in range(1, Number + 1):
value = int(input("Please enter the %d List Item = " %i))
avglist.append(value)
total = sum(avglist)
avg1 = mean(avglist)
avg2 = reduce(lambda x, y: x + y, avglist) / Number
#avg2 = reduce(lambda x, y: x + y, avglist) /len(avglist)
print('\nThe Sum Of List Items = ', total)
print('\nThe Average Of List Items = ', avg1)
print('\nThe Average Of List Items = ', avg2)
Total Number of List Items = 6
Please enter the 1 List Item = 19
Please enter the 2 List Item = 98
Please enter the 3 List Item = 56
Please enter the 4 List Item = 49
Please enter the 5 List Item = 77
Please enter the 6 List Item = 67
The Sum Of List Items = 366
The Average Of List Items = 61
The Average Of List Items = 61.0
这个 python 程序使用 for 循环来迭代列表项,并计算所有列表元素的总和和平均值。
avglist = []
total = 0
Number = int(input("Total Number of List Items = "))
for i in range(1, Number + 1):
value = int(input("Please enter the %d List Item = " %i))
avglist.append(value)
for i in range(Number):
total = total + avglist[i]
avg = total / Number
print('\nThe Sum Of List Items = ', total)
print('\nThe Average Of List Items = ', avg)
Total Number of List Items = 7
Please enter the 1 List Item = 22
Please enter the 2 List Item = 13
Please enter the 3 List Item = 43
Please enter the 4 List Item = 67
Please enter the 5 List Item = 98
Please enter the 6 List Item = 11
Please enter the 7 List Item = 26
The Sum Of List Items = 280
The Average Of List Items = 40.0
在这个 Python 例子中,listAverage 函数接受一个列表,并返回所有列表项的总和和平均值。
def listAverage(avglist):
total = 0
for i in range(Number):
total = total + avglist[i]
avg = total / len(avglist)
return total, avg
avglist = []
Number = int(input("Total Number of List Items = "))
for i in range(1, Number + 1):
value = int(input("Please enter the %d List Item = " %i))
avglist.append(value)
total, avg = listAverage(avglist)
print('\nThe Sum Of List Items = ', total)
print('\nThe Average Of List Items = ', avg)
Total Number of List Items = 8
Please enter the 1 List Item = 2
Please enter the 2 List Item = 9
Please enter the 3 List Item = 11
Please enter the 4 List Item = 24
Please enter the 5 List Item = 58
Please enter the 6 List Item = -11
Please enter the 7 List Item = 17
Please enter the 8 List Item = 99
The Sum Of List Items = 209
The Average Of List Items = 26.125