python - 如何在 Counter 类中实现 __add__ 方法?
问题描述
我想在 Counter 类中实现add方法。无需导入计数器。
我在代码中看到了一个想法,但它总是给我一个错误。
class MyCounter:
def __init__(self, s=None):
self.q = {}
for x in s:
self.add(x)
def __repr__(self):
return str(self.q)
def add (self,x):
if x in self.q:
self.q[x] = self.q[x] + 1
else:
self.q[x]=1
def __add__(self, args):
new_dict = self.q
for x in new_dict:
if x in args:
u=args.get(x)
new_dict[x] = new_dict[x]+ u
else:
new_dict[x]=1
这就是我要的
a= MyCounter("hahahahha")
a+ MyCounter("hahhahahah")
new_dict = {'h': 11, 'a': 8}
如果我尝试它的错误代码
TypeError:“MyCounter”类型的参数不可迭代
解决方案
您的线路:
if x in args:
本质上是:
if x in MyCounter("hahhahahah"):
但MyCounter
不支持in
运营商。
您可能想检查一下q
:
if x in args.q:
您还可in
以为您的类实现运算符(使用该__contains__
方法),或者dict
直接从子类(这就是这样collections.Counter
做的)。
您在这里也有同样的问题:
u=args.get(x)
MyCounter
没有get()
方法,你想用这个代替:
u=args.q.get(x)
推荐阅读
- javascript - 运行测试时获取“不变违规:本机模块不能为空。”
- python - 通过并行处理将 xls 批量转换为 csv
- python - 从熊猫的timedelta列中提取天数
- python - PyTorch - 如何在评估模式下停用辍学
- html - HTML 和 CSS:带有文本的完整响应式图像上的灰色叠加背景
- java - 如何翻转javafx滑块的轴
- robotframework - 在 robots/RIDE 中使用 jython 从 output.xml 重新运行失败的测试用例
- javascript - window.onload 在 IE 8、9 加载动态脚本之前执行
- html - 如何使用 this.sanitizer.bypassSecurityTrustStyle 作为背景色
- scala - 在调整大小之前,传单地图无法正确显示