将操作元素明智地应用于嵌套列表中的所有列表

Apply operation element wise to all lists in nested list

我已经嵌套了,列表例如:

[[1.0, 2.0, 3.0],  
 [3.0, 3.0, 3.0]]

我需要的是:

[2.0, 2.5, 3.0]  

因此结果列表的每个元素都是按列嵌套列表的列表的平均值。

在 Python 2.7 中最有效的方法是什么。我想解决方案会涉及使用地图,但我看不到将其应用于此任务的正确方法。

您可以使用 zip and map. Use zip to transpose the matrix and then map every column to its mean with the help of sum 对列中的所有值求和。

values = [[1, 2, 3], [3, 3, 3]]
averages = map(lambda x: sum(x)/float(len(x)), zip(*values))

print averages

输出:

[2.0, 2.5, 3.0]

使用zip和列表理解:

lists = [[1.0, 2.0, 3.0], [3.0, 3.0, 3.0]]
averages = [sum(l)/len(l) for l in zip(*lists)]

您可以 zip 列表列表 mapstatistics.mean:

from statistics import mean
list(map(mean, zip(*lst)))

这个returns:

[2, 2.5, 3]
list(map(lambda x,y: (x+y)/2.0, [1, 2, 3], [3, 3, 3]))

输出:

[2.0, 2.5, 3.0]

您可以使用库 'numpy' 进行非常高效的计算。

import numpy as np

a = np.array([[1,2,3], [3,3,3]])
np.mean(a, axis=0)