添加lis的元素

2024-03-29 11:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试添加列表中的所有元素并找到其平均值。你知道吗

[[0.7,5,6,4,2,45,7,8,5,3,2,6,8,3,2,2,5,4]]

找到平均值的代码是:

avg = sum(lst)/len(lst)

错误:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

我认为这是因为它是一个列表的列表,但我不想改变我的列表输出,因为这个输出花了我将近100行代码。 如何添加所有这些元素而不损坏代码? 液化天然气-Python


Tags: 代码元素列表forlentype错误int
3条回答

应该是avg = sum(lst[0])/len(lst[0])

尝试使用流行音乐:

list = [[1,2,3,4,5]]

innerList = list.pop()

avg = sum( innerList ) / len ( innerList )

print avg

结果:

3

你可以用numpy做这个。你知道吗

In [1]: import numpy as np
In [2]: lst = [[0.7,5,6,4,2,45,7,8,5,3,2,6,8,3,2,2,5,4]]
In [3]: np.mean(lst[0])
Out[3]: 6.5388888888888888

相关问题 更多 >