我正在尝试创建两个默认词典的联合。以下是我班级中方法的代码:
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()
答案 0 :(得分:0)
定义是
def __add__(self,other):
因此,您应该将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
答案 1 :(得分: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类中实现 setitem 和 getitem 方法以允许[]表示法。您可以实现它们或只访问属性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对象