|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class CountList:
def __init__(self,*args):
self.value = [x for x in args]
self.count = {}
self.count.fromkeys(range(len(self.value)),0)
def __len__(self):
return len(self.value)
def __getitem__(self,key):
self.count[key] += 1
return self.value[key]
为什么我定义字典的方式在运行中会报错呢?
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
c1[3]
File "D:/Python39/047自定义列表.py", line 13, in __getitem__
self.count[key] += 1
KeyError: 3
改写成书上那样就不报错
self.count={}.fromkeys(range(len(self.value)),0)
因为你的字典是个空字典,取不出数据
class CountList:
def __init__(self,*args):
self.value = [x for x in args]
self.count = {}
self.count = self.count.fromkeys(range(len(self.value)),0) # 这里要赋值
def __len__(self):
return len(self.value)
def __getitem__(self,key):
self.count[key] += 1
return self.value[key]
|
|