嗨,我正在上这门课
class multiset(dict):
def __new__(cls,iterabile):
d = dict()
for i in iterabile:
if i not in d.keys():
d[i] = iterabile.count(i)
return super().__new__(cls,d)
Run Code Online (Sandbox Code Playgroud)
此类是一个自定义字典,它从输入列表创建一个字典,其中键是元素,值是键元素在列表中出现的次数。问题是 super().__new__(cls,d) 返回此错误:
回溯(最近一次调用最后一次):
文件“”,第 1 行,m = multiset([1,1,1,2,1,3,2,3])
类型错误:无法将字典更新序列元素 #0 转换为序列
更改为 using__init__()并且不创建显式的新字典,因为self它已经是一个字典,因为 multiset 继承自 dict:
class multiset(dict):
def __init__(self,iterable):
for i in iterable:
if i not in self.keys():
self[i] = iterable.count(i)
m = multiset([1,1,1,2,1,3,2,3])
print( m )
# prints: {1: 4, 2: 2, 3: 2}
Run Code Online (Sandbox Code Playgroud)
但正如 ndclt 指出的那样,collections.Counter已经这样做了。
| 归档时间: |
|
| 查看次数: |
671 次 |
| 最近记录: |