资讯动态

python 在 Python 中求列表的和与平均值

发布时间:2026/9/25 20:19:12 来源:尧图企业网站定制
在列表中求那个列表的各项数值加起来的总和, 以及它们的平均数值。原文: . . org/find-sum-and--of-list-in-/给定了一个列表, 现在需要去把列表里的数字加起来看看它们的总和是多少, 然后再看看平均值, 关于平均这个数, 它的意思就是拿这堆数的总和除以里面有多少个数字就行了。示例:Input: [4, 5, 1, 2, 9, 7, 10, 8]Output:sum 46average 5.75Input: [15, 9, 55, 41, 35, 20, 62, 49]Output:sum 286average 35.75就是选择第一种办法, 也就是天真这种办法。在这个方法中, 我们会依次去遍历那个列表, 并且把找到的每一个元素都添加到一个用作计数的变量里去,这个计数是专门用来保存那些第 i 个元素之和的数值的, 在求和的工作完成之后呢, 我们就拿得到的总和问题除以变量的总量是多少, 从而最终计算出那个平均值。示例:3# Python program to find the sum# and average of the listL [4, 5, 1, 2, 9, 7, 10, 8]# variable to store the sum of# the listcount 0# Finding the sumfor i in L:count i# divide the total elements by# number of elementsavg count/len(L)print(sum , count)print(average , avg)输出:sum 46average 5.75第二种方法, 是选择去使用 sum() 这个方法。sum()方法返回作为参数传递的列表的和, 然后我们将总和除以len()方法得到平均值。示例:3# Python program to find the sum# and average of the listL [4, 5, 1, 2, 9, 7, 10, 8]# using sum() methodcount sum(L)# finding averageavg count/len(L)print(sum , count)print(average , avg)输出:sum 46average 5.75

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑