Python中列表属性的平均值

2024-10-02 10:33:02 发布

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

我有一个对象列表,其中有一个属性(attributions),我希望将其平均化(按元素)。最好的方法是什么?你知道吗

我将对象(ExplanationObjects)放在一个列表attr中,每个对象都有一个属性attributions,我希望以元素方式将其平均化。例如,如果我有:

a.attribution=[[2,1],[4,6]]

以及

b.attribution=[[4,3],[8,8]] 

我想得到

[[3,2],[6,7]]

现在,我用

(sum(a.attribution for a in attrs))/len(attrs) 

这是最好的方法,还是有其他方法(numpy首选)你会建议?你知道吗


Tags: 对象方法in元素列表for属性方式
1条回答
网友
1楼 · 发布于 2024-10-02 10:33:02

如果将属性转换为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]]

相关问题 更多 >

    热门问题