Python口述类

Python口述类,python,class,dictionary,Python,Class,Dictionary,我试图让我的类工作,但我似乎只能添加2个项目,我不能添加重复的项目 我也尝试过使用for循环,但我似乎也无法让它工作 要添加的单词列表: words = Bag() words.add('once') words.add('twice') words.add('twice') 我的代码: class Bag: def __init__(self): """Create a new empty bag.""" self.bag = dict()

我试图让我的类工作,但我似乎只能添加2个项目,我不能添加重复的项目

我也尝试过使用for循环,但我似乎也无法让它工作

要添加的单词列表:

words = Bag()
words.add('once')
words.add('twice')
words.add('twice')
我的代码:

class Bag:

    def __init__(self):
        """Create a new empty bag."""
        self.bag = dict()


    def add(self, item):
        """Add one copy of item to the bag. Multiple copies are allowed."""

        if not item in self.bag:
            self.bag[item] = 1
        else:
            self.bag[item] += 1

        print(self.bag)

您希望结果看起来像{'one':1,'tweep':2,'tweep':3}

这是不可能的,您不能在一个dict中多次使用同一个键。但是您可以使用以下代码获得类似[{'one':1},{'tweep':2},{'tweep':3}]的结构:

from collections import defaultdict


class Bag:
    def __init__(self):
        """Create a new empty bag."""
        self.index = 0
        self.bag = []


    def add(self, item):
        """Add one copy of item to the bag. Multiple copies are allowed."""
        self.index += 1
        self.bag.append({item: self.index})

但是你的代码很有效。你的代码对我来说非常有效。你有错误吗?您的预期输出与实际输出是什么?对于self.bag.values中的x:printX感谢您的回复,我的代码工作到一定程度我无法让我的代码在我的字典中添加“两次”两次只显示2个条目,而不是3个条目谢谢您的回复,我的代码工作到一定程度,我无法让我的代码在我的字典中添加“两次”两次,只显示2个条目,而不是3个条目显示正确的结果是什么?{'once':1,'TWEEP':2}正确吗?正确的结果应该是这样的{'once':1,'TWEEP':2,'TWEEP':3}我编辑了我的答案。你不能得到你想要的,但你可以得到类似的东西。天才!非常感谢。我现在明白我错在哪里了!