簡體   English   中英

如何使用__add__添加兩個字典對象?

[英]How to add two dictionary object with __add__?

例如,我有兩個對象:

例如(['d','c','d','a'])

例如(['a','b','c','x','b','a'])

這些對象將產生以下字典:

{'d':2,'c':1,'a':1}

{'a':2,'b':2,'c':1,'x':1}

如何添加這兩個字典對象以產生如下結果:

實施例(A [2],B [2],C [2],d [2],X [1])

Ex操作數均不應更改。

所以我想出了下面的代碼:

def __add__(self, another):
    r = self._val.copy()
    for key, val in another._val.items():
        if key in r:
            r[key] += val
        else:
            r[key] = val
    return r

但這似乎不能正常工作,並且在自動檢查器上出現錯誤,我必須要經歷。

我必須使用dunder add,並且兩個Ex對象都無法更改。

任何建議,將不勝感激!

使用Counter做這樣的事情,並記住在繼承上組成 (或復合重用原理),因此使用counter時,您的Ex類dunder add應該看起來像這樣:

from collections import Counter


class Ex:
    def __init__(self, characters):
        self.counter = Counter(characters)

    def get_result(self):
        return dict(self.counter.items())

    def __add__(self, other):
        if not isinstance(other, Ex):
            return NotImplemented
        result = Ex([])
        result.counter = self.counter + other.counter
        return result


ex_1 = Ex(['d', 'c', 'd', 'a'])
ex_2 = Ex(['a', 'b', 'c', 'x', 'b', 'a'])
ex_3 = ex_1 + ex_2

print(ex_1.get_result())  # {'d': 2, 'c': 1, 'a': 1}
print(ex_2.get_result())  # {'a': 2, 'b': 2, 'c': 1, 'x': 1}
print(ex_3.get_result())  # {'d': 2, 'c': 2, 'a': 3, 'b': 2, 'x': 1}

如果您的目標是添加兩個字典,則可以使用'update'Ex dict1 = {'a':1,'b':2}和dict2 = {'a':2,'c':3}然后使用dict1。 update(dict2)將dict2的值更新為dict1。 當您輸出dict1時,它將輸出{'a':2,'b':2,'c':3}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM