鱼C论坛

 找回密码
 立即注册
查看: 1097|回复: 2

[已解决]小甲鱼入门学习python第46讲动手题为啥不用列表中的元素作为字典的key??

[复制链接]
发表于 2018-4-27 00:36:17 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 三与七之间 于 2018-4-27 00:38 编辑

Screenshot from 2018-04-26 09-27-25.png

图片里是那道题,小甲鱼说要改造一下原来的代码,所以,改用用列表去存储元素被访问的次数,小甲鱼的想法是如下图:
Screenshot from 2018-04-26 09-32-33.png

可是我觉得直接把列表的元素当做字典的key不是也可以解决问题吗??这样就不用考虑那么多了。。。。我现在的疑惑的是,是不是我没理解小甲鱼的题意啊??下边是我的代码,各位大侠瞅瞅我这么做是符合题意的吧??

  1. class CountList:

  2.     def __init__(self, *args):
  3.         self.mylist = [each for each in args]
  4.         self.mycount = {}.fromkeys(self.mylist, 0)

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

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

  10.     def __setitem__(self, key, value):
  11.         self.mylist[key] = value

  12.     def __delitem__(self, key):
  13.         del self.mylist[key]
  14.         self.mycount.pop(self.mylist[key])

  15.     def append(self, item):
  16.         self.mylist.append(item)
  17.         self.mycount[item] = 0

  18.     def pop(self, key=None):
  19.         if key == None:
  20.             self.item = self.mylist.pop()
  21.             self.mycount.pop(self.item)
  22.         else:
  23.             self.item = self.mylist.pop(key)
  24.             self.mycount.pop(self.item)
  25.         return self.item

  26.     def remove(self, item):
  27.         if item not in self.mylist:
  28.             print("%s not exit in the list!" % item)
  29.         else:
  30.             self.mylist.remove(item)
  31.             self.mycount.pop(item)

  32.     def clear(self):
  33.         self.mylist.clear()
  34.         self.mycount.clear()

  35.     def insert(self, index, value):
  36.         self.mylist.insert(index, value)
  37.         self.mycount[value] = 0

  38.     def counter(self, index):
  39.         return self.mycount[self.mylist[index]]
复制代码
最佳答案
2018-4-27 01:04:14
初步看了下,应该没问题。字典的本质就是映射,只要不发生collection就没事
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-4-27 01:04:14 | 显示全部楼层    本楼为最佳答案   
初步看了下,应该没问题。字典的本质就是映射,只要不发生collection就没事
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-4-27 09:52:44 | 显示全部楼层
ABC23 发表于 2018-4-27 01:04
初步看了下,应该没问题。字典的本质就是映射,只要不发生collection就没事

嗯呢,知道啦~~谢谢~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-27 01:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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