示例:x = [[1,3,2],[4,5,6],[7,8,9]]
我尝试使用:
sum(x) / len(x)
,但似乎给了我这个错误
(TypeError:+不支持的操作数类型:“ int”和“ list”)
该列表由用户使用以下命令输入:average_list([]),并且每个方括号中可以包含任意数量的数字。
答案 0 :(得分:0)
您可以sum
内部列表的总和:
x = [[1,3,2],[4,5,6],[7,8,9]]
s = sum(sum(a) for a in x)
l = sum(len(a) for a in x)
print(s / l) # 5.0
答案 1 :(得分:0)
使用numpy
import numpy as np
x = np.array(x)
avg = np.sum(x)/np.size(x) # avg = 5
答案 2 :(得分:0)
x = [i for sublist in x for i in sublist]
avg = sum(x)/len(x)
将列表弄平后得到答案
答案 3 :(得分:0)
这将为您提供列表列表的平均值和完整列表的平均值。
x = [[1,3,2],[4,5,6],[7,8,9]]
new_list = [sum(l)/len(l) for l in x]
print(sum(new_list)/len(new_list))
输出:
5.0
答案 4 :(得分:0)
一种更有效的方法是:
x = [[1,3,2],[4,5,6],[7,8,9]]
#stripping square brackets
elementsString = ''.join( c for c in str(x) if c not in '[]' )
total = 0
numberOfElements = 0
#converting the string numbers into int
for i in elementsString.split(','):
#using int but can be also float for example
i = int(i)
numberOfElements += 1
total += i
average = total/numberOfElements
print(average)
#5.0 is the answer in your case
答案 5 :(得分:-2)
您是要查找(x)整个列表的总和还是每个单元格的总和?