我正在尝试使用for循环来获取每周和python中的月份的平均值:
sum = 0
sumA = 0
sumB = 0
sumC = 0
sumD = 0
week1 = (35,38,30,34,27,40,39)
week2 = (35,38,30,34,27,40,39)
week3 = (35,38,30,34,27,40,39)
week4 = (35,38,30,34,27,40,39)
for x in (week1):
sum = sum + week1[x]
avg1 = (sum + week1[x]) / 7
for y in (week2):
sumA = sumA + week2[y]
avg2 = (sumA + week2[y]) / 7
for z in (week3):
sumB = sumB + week3[z]
avg3 = (sumB + week3[z]) / 7
for k in (week4):
sumC = sumC + week4[k]
avg4 = (sumC + week4[k]) / 7
sumD = sum + sumA + sumB + sumC
avg = (sum + sumA + sumB + sumC) / 28
就是这样但不正确。我能得到一些帮助吗
答案 0 :(得分:5)
假设您使用的是Python 2.x,两个整数的/
运算符使用整数divsion,i。即除法的结果向下舍入到下一个整数。在交互式解释器中尝试:
>>> 5/3
1
要获得正确的浮点除法,请使用
from __future__ import division
或首先将其中一个操作数转换为float
avg = float(sum + sumA + sumB + sumC) / 28
答案 1 :(得分:4)
您不需要这些循环。这是一个简单的例子:
>>> week1 = (35,38,30,34,27,40,39)
>>> average1 = sum(week1) / len(week1)
>>> average1
34
如评论中所述:
上面的例子(在Python 2.x中)如果你想要“真正的”除法(例如34.71),则需要一个部分转换为浮动。
在Python 3.x中,单/
除法默认为'true'除法,因此上面的代码段是正确的(尽管average1
的结果值不同)
答案 2 :(得分:3)
这里有几个问题。首先,for x in lst
产生lst
的元素,而不是索引。其次,您在元素中添加两次,一次更新sum
,然后再次更新avg
。只需在列表外计算avg
即可。第三,除以float
而不是int
以防止截断:
for x in (week1):
sum = sum + x
avg1 = sum / 7.
答案 3 :(得分:2)
list = [....]
avg = sum(list)/float(len(list))
答案 4 :(得分:1)
>>> def ave(numbers):
... return sum(numbers) / len(numbers)
...
>>> week1 = (35,38,30,34,27,40,39)
>>> week2 = (35,38,30,34,27,40,39)
>>> week3 = (35,38,30,34,27,40,39)
>>> week4 = (35,38,30,34,27,40,39)
>>> ave(week1)
34
>>> ave(week1+week2+week3+week4)
34
>>>
<小时/> 正如其他人所指出的,如果你想要一个非截断的结果
,请使用
from __future__ import division