|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 三与七之间 于 2018-4-27 00:38 编辑
图片里是那道题,小甲鱼说要改造一下原来的代码,所以,改用用列表去存储元素被访问的次数,小甲鱼的想法是如下图:
可是我觉得直接把列表的元素当做字典的key不是也可以解决问题吗??这样就不用考虑那么多了。。。。我现在的疑惑的是,是不是我没理解小甲鱼的题意啊??下边是我的代码,各位大侠瞅瞅我这么做是符合题意的吧??
- class CountList:
- def __init__(self, *args):
- self.mylist = [each for each in args]
- self.mycount = {}.fromkeys(self.mylist, 0)
- def __len__(self):
- return len(self.mylist)
- def __getitem__(self, key):
- self.mycount[self.mylist[key]] += 1
- return self.mylist[key]
- def __setitem__(self, key, value):
- self.mylist[key] = value
- def __delitem__(self, key):
- del self.mylist[key]
- self.mycount.pop(self.mylist[key])
- def append(self, item):
- self.mylist.append(item)
- self.mycount[item] = 0
- def pop(self, key=None):
- if key == None:
- self.item = self.mylist.pop()
- self.mycount.pop(self.item)
- else:
- self.item = self.mylist.pop(key)
- self.mycount.pop(self.item)
- return self.item
- def remove(self, item):
- if item not in self.mylist:
- print("%s not exit in the list!" % item)
- else:
- self.mylist.remove(item)
- self.mycount.pop(item)
- def clear(self):
- self.mylist.clear()
- self.mycount.clear()
- def insert(self, index, value):
- self.mylist.insert(index, value)
- self.mycount[value] = 0
- def counter(self, index):
- return self.mycount[self.mylist[index]]
复制代码
初步看了下,应该没问题。字典的本质就是映射,只要不发生collection就没事
|
|