基本上,该函数应该提供列表中列表的平均值.例:
lst = [[46, 27, 68], [26, 65, 80], [98, 56, 35], [98, 65, 0]]
average(lst)
>>> [47.0, 57.0, 63.0, 54.33333333333333]
Run Code Online (Sandbox Code Playgroud)
我的代码:
def average(l):
for i in range(len(l)):
for j in range(len(l[0])):
l[i] / l[j]
return l
Run Code Online (Sandbox Code Playgroud)
我的编码显示一个错误标志,上面写着"TypeError:/ support'和'list'"不支持的操作数类型.我不知道我做错了什么.
首先 - 缩进很重要:
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.
Run Code Online (Sandbox Code Playgroud)
第二 - 使用有用的变量名称.一个角色通常没有帮助.
def average(lst):
for lstNum in range(len(lst)):
for sublistItem in range(len(lst[lstNum])):
lst[lstNum] / lst[sublistItem] # <-- ??
return lst
Run Code Online (Sandbox Code Playgroud)
现在应该很清楚(呃)sublistItem,用作lst的索引,没有任何意义.如果我们用lst [lstNum] [sublistItem]替换lst [sublistItem]它会更好,但是你会将列表除以整数,这也没有意义.
第三 - 模式
for num in range(len(lst)):
val = lst[num]
Run Code Online (Sandbox Code Playgroud)
是非Pythonic; 如果你真的需要,请使用
for num,val in enumerate(lst):
Run Code Online (Sandbox Code Playgroud)
相反,甚至更好,
for val in lst:
Run Code Online (Sandbox Code Playgroud)
第四,要获得平均值,您需要将列表总和除以其中的项目数 ; 在您的代码中,您既没有这样做.分别尝试sum(lst)和len(lst).