[英]Python 2d list average columns
I have a 2d list of the format peaks = [[3.56, 7.94, 3.56,... ], [...]]
.我有一个格式peaks = [[3.56, 7.94, 3.56,... ], [...]]
的二维列表。
I'm trying to use the following list comprehension to create a list containing the averages of each of the columns of peaks
.我正在尝试使用以下列表理解来创建一个包含peaks
每一列的平均值的列表。 That looks like this,看起来像这样
[sum(peaks[:,i])/len(peaks) for i in range(len(peaks[0]))]
As far as I know, this is proper column-slicing and list comprehension syntax, and yet I get this error:据我所知,这是正确的列切片和列表理解语法,但我得到了这个错误:
TypeError: list indices must be integers or slices, not tuple
Can someone help me out?有人可以帮我吗?
First you can transform the row to column in your list, for example:首先,您可以将列表中的行转换为列,例如:
[[1,2,3],[4,5,6]] to [(1, 4), (2, 5), (3, 6)]
Then you can use statistics.mean()然后你可以使用statistics.mean()
>>>import statistics
>>>l=[]
>>>peaks = [[1,2,3],[4,5,6]]
>>>peak=[*zip(*peaks)]
>>>peak
[(1, 4), (2, 5), (3, 6)]
>>>for i in peak:
>>> l.append(statistics.mean(i))
>>>l
[2.5, 3.5, 4.5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.