在类实例中对词典中的值求和

时间:2018-04-02 13:48:57

标签: python oop dictionary

我想在以下所有实例中总结所有值。 有没有办法将实例中的所有值加在一起?

class Node:
    def __init__(self, name, neighbour):
        self.neighbour = {}
        self.name = name
        self.neighbour = dict(neighbour)

N1 = Node('N1', {'N7': 15, 'N6': 5, 'N5': 20, 'N4': 20, 'N2': 10})
N2 = Node('N2', {'N4': 10, 'N3': 5})
N3 .... N10

编辑,试图让它更清晰

2 个答案:

答案 0 :(得分:0)

如果您定义__add__课程的Node方法,则可以使用内置:sum()

@property
def _total(self): #helper property to get sum of single node
    return sum(self.neighbor.values())

def __add__(self, other):
    if type(other) == self.__class__: #first two elements taken with `sum()` will be
                                      # of type: <Node>
        return self._total + other._total
    elif type(other) == int:  #subsequent additions (because sum() works like reduce())
                              # will add running total with next node
        return self._total + other
    else:  #don't bother trying to handle all types..
        raise TypeError("can't add {} with {}".format(self.__class__, other.__class__))

然后得到总和:sum([N1, N2, N3, ...N10])

答案 1 :(得分:0)

您想要的输出并不完全清楚。以下是对您的问题的3种解释。

我使用字典存储您的类实例,因为这是存储可变数量变量的推荐方法。

class Node:
    def __init__(self, name, neighbour={}):
        self.name = name
        self.neighbour = dict(neighbour)

N = {1: Node('N1', {'N7': 15, 'N6': 5, 'N5': 20, 'N4': 20, 'N2': 10}),
     2: Node('N2', {'N4': 10, 'N3': 5}),
     3: Node('N3', {'N5': 20, 'N2': 15, 'N4': 5})}

### sum by node ###

sum_by_node = {k: sum(v.neighbour.values()) for k, v in N.items()}
# {1: 70, 2: 15, 3: 40}

### sum across nodes by key ###

keys = set().union(*(v.neighbour for v in N.values()))
sum_by_key = {k: sum(v.neighbour.get(k, 0) for v in N.values()) for k in keys}
# {'N2': 25, 'N3': 5, 'N4': 35, 'N5': 40, 'N6': 5, 'N7': 15}

### sum across nodes and across keys ###

sum_all = sum(sum(v.neighbour.values()) for v in N.values())
# 125