Python中列表中浮点值的平均数或均值
我有一个列表 lt[][]
,里面存的是浮点数值。现在当我想计算这些浮点数的平均值时,出现了错误,提示说 float object has no attribute mean
或者 float object is not iterable
。我使用的代码是:
for i in range(100):
acc_pos = marks[i][5] # list of float values
pos_acc.append((sum(acc_pos))/(len(acc_pos))) # when used then 2nd error comes
neg_acc.append(acc_pos.mean()) # when used then 1st error comes
注意:我并不是同时使用这两种方法,而是选择其中一种。错误是根据我使用的那一行代码出现的。
更新:marks 是一个列表的列表,类似于 [78.3,[1,0,,1...],...]
。所以通过写 marks[i][5]
,我想访问每一行的第0个元素。
2 个回答
0
计算一组浮点数的平均值的方法可以在这个StackOverflow问题中找到。
如果你想计算多个列表的整体平均值,下面的方法可以使用,即使这些列表的长度不一样也没问题:
numerator = reduce(lambda x, y: x + sum(y), marks, 0.0)
denominator = reduce(lambda x, y: x + len(y), marks, 0.0)
result = numerator / denominator
5.0 # result
顺便提一下,关于调试(我似乎没有权限在问题下评论)——Python是一种解释型语言,不会像编译型语言那样给出编译错误。Python的交互式控制台让调试变得简单。你至少可以通过在控制台中执行以下操作来诊断你上面提到的错误信息:
# (0) define the 'marks' test variable
marks = [[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]
# (1) do the fist iteration of the loop by hand
i = 0
acc_pos = marks[i][0]
acc_pos.mean() # Error occurs
# (2) print out the variable
acc_pos
# At this point you realize acc_pos is a float not a list
有用的资源:Python 2的教程,以及Python 3的教程。如果你已经会其他编程语言,这些教程比Udemy或Code Academy等网站要快。
3
我觉得问题出在第二行。
acc_pos = marks[i][0]
那一行代码并没有把一系列的浮点数放进acc_pos里,而只是把pos[i][0]这个位置的一个浮点数放进了矩阵里。
把它换成
acc_pos = marks[i]