二维列表的平均值
基本上,这个函数应该计算列表中每个子列表的平均值。
举个例子:
lst = [[46, 27, 68], [26, 65, 80], [98, 56, 35], [98, 65, 0]]
average(lst)
>>> [47.0, 57.0, 63.0, 54.33333333333333]
这是我的代码:
def average(l):
for i in range(len(l)):
for j in range(len(l[0])):
l[i] / l[j]
return l
我的代码出现了一个错误提示,内容是“TypeError: unsupported operand type(s) for /: 'list' and 'list'”。我不太明白我哪里出错了。
6 个回答
有一个问题是,在这行代码中
l[i] / l[j]
你没有把这个操作的结果保存到任何地方,也没有以任何方式显示出来。你的程序确实进行了这个操作,但没有把结果存下来。所以当你在函数最后返回l的时候,你得到的只是你最开始传入的那个东西。
顺便提一下,这里有一些你可能想看看的内容。虽然它不完全符合你的需求,但你应该能把它改成你需要的样子。可以参考这个教程:http://docs.python.org/tutorial/stdlib.html#quality-control
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print average([20, 30, 70])
40.0
"""
return sum(values, 0.0) / len(values)
想想你提到的对象 l[i]
的类型是什么。最开始的那个就是 l[0]
,它的值是 [95, 92, 86]
。换句话说,它是一个列表。
如果你确定它总是只有两层深,你需要用类似下面的东西:
for each sublist in l
for each item in sublist
sum = sum + item
avg = sum / len(sublist)
append avg to returnlist
这里用伪代码写得很仔细,因为自己搞明白这些东西会更有趣。
如果你不知道这些列表嵌套了多少层,你就需要考虑递归,也就是类似下面的东西:
proc:
for each sublist in list
if sublist has sublists
call proc with each sublist
else
call avg on sublist
首先 - 缩进很重要:
Then thou must space to four. Four shall be the number of the
spacing and the number of the spacing shall be four. Five shalt
thou not space, neither shalt thou space three, excepting that
thou then proceedeth to four. Tab characters are right out.
第二 - 使用有帮助的变量名。 一个字母的变量名通常没什么帮助。
def average(lst):
for lstNum in range(len(lst)):
for sublistItem in range(len(lst[lstNum])):
lst[lstNum] / lst[sublistItem] # <-- ??
return lst
现在应该更清楚了,sublistItem这个名字用来表示lst中的索引是没有意义的。如果我们把lst[sublistItem]换成lst[lstNum][sublistItem],那会更好,但这样你就是在用一个整数去划分一个列表,这同样没有意义。
第三 - 这个模式
for num in range(len(lst)):
val = lst[num]
不符合Python的风格;如果你真的需要这样做,可以使用
for num,val in enumerate(lst):
更好的是,
for val in lst:
第四,要计算平均值,你需要把列表的总和除以其中的项数;在你的代码中,你既没有做这两件事。试试分别用sum(lst)和len(lst)。