1

我正在尝试创建两个默认词典的联合。这是我班级中方法的代码:

def __add__(self,right):
    mergedbag = copy.copy(self.bag_value)
    for item in right:
        if item not in mergedbag:mergedbag[item] = 0
        mergedbag[item] += right[item]
    return mergedbag

我创建了两个默认字典:

b = Bag(['d','a','b','d','c','b','d'])
c = Bag(['d','a','b','d','c','b','d'])

的结果

print(b+c)

应该是联合后元素的总数..

Bag(a[a],b[4],c[3],d[6])

这是我不断收到的错误:

    Traceback (most recent call last):
  File "D:\workspace33\courselib\driver.py", line 229, in driver

Command[print(b+c)]:     exec(old,local,globl)
  File "<string>", line 1, in <module>
  File "D:\workspace33\Project2\src\bag.py", line 58, in __add__
    mergedbag[item] += right[item]
TypeError: 'Bag' object is not subscriptable

这是新代码:

class Bag:
def __init__(self, items = []):
    self.bag_value = defaultdict(int)
    for item in items:
        self.bag_value[item] += 1


def __repr__(self):
    bag_list = []
    for item, count in self.bag_value.items():
        bag_list.extend(list(item*count))
    return 'Bag(' + str(bag_list) + ')'



def __str__(self):
    return 'Bag(' + ','.join(str(item) + '[' + str(count) + ']' for item, count in self.bag_value.items()) + ')'



def __len__(self):
    bag_len = 0
    for value in self.bag_value:
        bag_len += self.bag_value[value]
    return bag_len



def unique(self):
    return len(self.bag_value)




def __contains__(self, item):
    return item in self.bag_value



def count(self, item):
    return(self.bag_items.count(item))



def add(self, new):
    self.bag_value[new] += 1



def __add__(self,right):
    mergedbag = copy.copy(self.bag_value)
    for item in right:
        if item not in mergedbag:mergedbag[item] = 0
        mergedbag[item] += right[item]
    return mergedbag



def remove(self, item):
    if item in self.bag_items:
        del(item)
    else:
        raise ValueError(type_as_str(item) + ' not in bag.')



def __eq__(self, right):
    if type(right) is not Bag:
        raise TypeError('Cannot compare Bag with' + type_as_str(right) + '. Can only compare Bag with Bag')
    else:
        return (len(self) == len(right)) and  (self.unique() == right.unique())



def __ne__(self, right):
    return not self.__eq__(right)



def _bag_gen(self, bag_value):
    for item in self.bag_value:
        for count in range(self.bag_value[item]):
            yield item



def __iter__(self):
    return self._bag_gen(self.bag_value)



if __name__ == '__main__':
#     bag = Bag(['d','a','b','d','c','b','d'])
#     bag2 = Bag(['d','a','b','d','c','b','d'])
#     bag3 = Bag(['d','a','b','d','c','b'])
#     print(bag == bag2)
#     print(bag == bag3)
#     print(bag != bag2)
#     print(bag != bag3)
    import driver
    driver.driver()
4

2 回答 2

0

定义是

def __add__(self,other):

所以你应该合并 with 的内容,self.items然后other.items返回结果。

此外,不确定是否bag1+bag2会起作用,但我的 pyfu 很弱,您必须明确地遍历它们并将计数加在一起。

import copy

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

#
mergedBag = copy.copy(c) #might wanna use deepcopy?
for k in d:
    if k not in mergedBag: mergedBag[k] = 0
    mergedBag[k] += d[k]

print mergedBag
于 2015-01-26T20:55:22.743 回答
0

首先,需要注意的是,你的 Bag 类与 Counter 基本相同。如果您需要任何特定的扩展,只需从它继承即可。我想说以下代码只是解决了您在 Bag 类中自己实现的所有功能:

from collections import Counter

class Bag(Counter):
    pass

b = Bag(['d','a','b','d','c','b','d'])
c = Bag(['d','a','b','d','c','b','d'])

print (b)
print (c)
print (b+c)

如果您正在做一个学习练习,问题是您没有在 Bag 类中实现setitemgetitem方法以允许使用 [] 表示法。您可以实现它们或仅访问属性 bag_value:

def __add__(self, right):
    mergedbag = Bag()
    mergedbag.bag_value = copy.copy(self.bag_value)
    for item in right.bag_value.keys():
        mergedbag.bag_value[item] += right.bag_value[item]
    return mergedbag

一定要创建并返回一个 Bag 对象

于 2015-01-29T22:15:03.040 回答