|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 myckjx 于 2018-7-16 03:55 编辑
我发现这个题里用字典的update()方法蛮好的哦,比如remove(),append()就可以呀,其它方法没做但是感觉也应该可以吧......
- class Newlist:
- def __init__(self,*arge):
- self.list1 = [x for x in arge]
- self.dict1 = {}.fromkeys(range(len(arge)),0)
- def __len__(self):
- return len(self.list1)
- def __getitem__(self,key):
- self.dict1[key] += 1
- return self.list1[key]
- def __setitem__(self,key,value):
- self.dict1[key] += 1
- self.list1[key] = value
- def append(self,value):
- self.dict1.update({len(self.list1):0})
- self.list1.append(value)
- def remove(self,value):
- self.dict2 = {}
- n = self.list1.index(value)
- for i in self.dict1:
- if i < n:
- self.dict2.update({i:self.dict1[i]})
- elif i > n:
- self.dict2.update({i-1:self.dict1[i]})
- self.dict1 = self.dict2.copy()
- self.list1.remove(value)
复制代码
>>> c = Newlist('a','b','c','d','e','f','g')
>>> c.list1
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> c.append('h')
>>> c[5]
'f'
>>> c[5]
'f'
>>> c.dict1
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 2, 6: 0, 7: 0}
>>> c.list1
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> c.remove('c')
>>> c.list1
['a', 'b', 'd', 'e', 'f', 'g', 'h']
>>> c.dict1
{0: 0, 1: 0, 2: 0, 3: 0, 4: 2, 5: 0, 6: 0}
>>>
蓝色字为内置方法,红色字为实现效果 |
|