首页 > 技术文章 > 记录列表中每个元素被访问的次数

themost 2017-03-11 22:48 原文

 1 #编写一个不可改变的自定义列表,要求记录列表中每个元素被访问的次数
 2 
 3 #定制一个容器类
 4 
 5 class Countlist:
 6     def __init__(self,*args):
 7         self.list=[x for x in args]#用户传入的参数构成一个列表
 8         self.count={}.fromkeys(range(len(self.list)),0)
 9         #建立self.count字典,用于记录列表self.list的索引值与访问次数的对应关系
10 
11     def __len__(self):
12         return len(self.list)
13 
14     def __getitem__(self,index):
15         self.count[index] += 1
16         return self.list[index]

  

•如果说你希望定制的容器是不可变的话,你只需要定义__len__()和__getitem__()方法。
•如果你希望定制的容器是可变的话,除了__len__()和__getitem__()方法,你还需要定义__setitem__()和__delitem__()两个方法。

推荐阅读