簡體   English   中英

Python字典在第一個之后不添加后續鍵

[英]Python dictionary not adding subsequent keys after the first

相當新的Python,我無法弄清楚這一點。 我去添加一個字典的密鑰,它添加它很好。 我甚至可以使用新值更新相同的密鑰,但是當我向字典添加第二個密鑰時,它不會添加第二個密鑰值對。

class CountedSet:
    def __init__(self):
        self.data = {}
    def __iadd__(self,other):
        if isinstance(other,int):
            self.data[other] = self.data.get(other, 0) + 1
            return self
        elif isinstance(other,CountedSet):
            #TODO::iterate through second countedSet and update self
            return self
    def __add__(self,obj):
        for key, value in obj.data.items():
            if len(self.data) == 0:
                self.data[key] = value
            elif self.data[key]:
                self.data[key] = self.data[key] + value
            else:
                self.data[key] = value
        return self
    def __getitem__(self,item):
        if item in self.data:
            return self.data.get(item)
        else:
            return None
    def __str__(self):
        for key, value in self.data.items():
            return("{%s,%s}" % (key,value))
a = CountedSet()
a += 17
a += 4
print(a)

當我希望看到{17,1} {4,1}時,這只會輸出{17,1}

你的__str__實現在for循環的第一次迭代時返回:

def __str__(self):
    for key, value in self.data.items():
        return("{%s,%s}" % (key,value)) # here

也許你想要的東西:

def __str__(self):
    return " ".join([{"{%s,%s}" % (k,v) for k, v in self.data.items()])

或者,沒有理解:

def __str__(self):
    items = []
    for key, value in self.data.items():
        items.append("{%s,%s}" % (key,value))
    return ' '.join(items)

暫無
暫無

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

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