Python中列表属性的平均值
我有一个对象列表,其中有一个属性(Python中列表属性的平均值,python,numpy,Python,Numpy,我有一个对象列表,其中有一个属性(attributes),我希望将其平均化(元素级)。最好的方法是什么 我将对象(ExplanationObjects)放在一个列表attr中,每个对象都有一个属性attributes,我希望以元素方式将其平均化。例如,如果我有: a.attribution=[[2,1],[4,6]] 及 我想得到 [[3,2],[6,7]] 现在,我通过使用 (sum(a.attribution for a in attrs))/len(attrs) 这是最好的方法,还
attributes
),我希望将其平均化(元素级)。最好的方法是什么
我将对象(ExplanationObjects
)放在一个列表attr
中,每个对象都有一个属性attributes
,我希望以元素方式将其平均化。例如,如果我有:
a.attribution=[[2,1],[4,6]]
及
我想得到
[[3,2],[6,7]]
现在,我通过使用
(sum(a.attribution for a in attrs))/len(attrs)
这是最好的方法,还是您建议使用另一种方法(numpy首选)?如果您将属性转换为numpy数组,您可以这样做。如果您在类中创建一个数组,这看起来会更整洁。我不知道你能不能做到,所以我的例子不能
import numpy as np
class C:
def __init__(self, attribution):
self.attribution = attribution
a=C([[2,1],[4,6]])
b=C([[4,3],[8,8]])
print(a.attribution)
print(b.attribution)
a_array = np.array(a.attribution)
b_array = np.array(b.attribution)
print((a_array + b_array)/2)
print(np.mean([a_array, b_array], axis=0))
print((a_array + b_array)//2) # preserve int
我用了几种不同的方法。您可以加2除2,也可以使用numpy.mean
输出
[[2, 1], [4, 6]]
[[4, 3], [8, 8]]
[[3. 2.]
[6. 7.]]
[[3. 2.]
[6. 7.]]
[[3 2]
[6 7]]
那么...怎么样
[[2, 1], [4, 6]]
[[4, 3], [8, 8]]
[[3. 2.]
[6. 7.]]
[[3. 2.]
[6. 7.]]
[[3 2]
[6 7]]