鱼C论坛

 找回密码
 立即注册
查看: 693|回复: 0

[技术交流] 047课后作业动动手好像可以用字典实现哦

[复制链接]
发表于 2018-7-16 03:42:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 myckjx 于 2018-7-16 03:55 编辑

我发现这个题里用字典的update()方法蛮好的哦,比如remove(),append()就可以呀,其它方法没做但是感觉也应该可以吧......
  1. class Newlist:
  2.     def __init__(self,*arge):
  3.         self.list1 = [x for x in arge]
  4.         self.dict1 = {}.fromkeys(range(len(arge)),0)

  5.     def __len__(self):
  6.         return len(self.list1)

  7.     def __getitem__(self,key):
  8.         self.dict1[key] += 1
  9.         return self.list1[key]

  10.     def __setitem__(self,key,value):
  11.         self.dict1[key] += 1   
  12.         self.list1[key] = value

  13.     def append(self,value):
  14.         self.dict1.update({len(self.list1):0})
  15.         self.list1.append(value)

  16.     def remove(self,value):
  17.         self.dict2 = {}
  18.         n = self.list1.index(value)
  19.         for i in self.dict1:
  20.             if i < n:
  21.                 self.dict2.update({i:self.dict1[i]})
  22.             elif i > n:
  23.                 self.dict2.update({i-1:self.dict1[i]})
  24.         self.dict1 = self.dict2.copy()
  25.         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}
>>>
蓝色字为内置方法红色字为实现效果
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-19 08:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表