python: ทำ ComplexDict แบบนึง
Submitted by wd on Sat, 2007-04-07 11:23
Topic:
อยากได้ดิกฯ แบบที่สามารถเติมข้อมูลได้ ทั้งแนวกว้างและแนวลึก
และให้เป็นข้อมูลแบบ Stack ด้วย
เราใช้วิธีการสร้างลิสต์ในดิกฯ โดย
สร้างคลาสชื่อ ComplexDict
ดังนี้
class ComplexDict: def __init__(self, key): self.__list__ = [] key = str(key) self.__list__.append([key,[]]) def add_key(self, key): if not self.has_key(key): self.__list__.append([key,[]]) def __repr__(self): return repr(dict(self.__list__)) def __getitem__(self, key): _keys = self.keys() if key in _keys: index = _keys.index(key) return self.__list__[index][1] def __delitem__(self, key): if self.has_key(key): self[key] = [] self.__list__.remove([key,[]]) def __setitem__(self, key, val): self.add_key(key) index = self.keys().index(key) self.__list__[index][1] = [val] def keys(self): return [i[0] for i in self.__list__] def values(self): return [i[1] for i in self.__list__] def has_key(self, key): if key in self.keys(): return True else: return False
ทดสอบ
>>> s=ComplexDict('a') >>> s {'a': []} >>> s.add_key('b') >>> s {'a': [], 'b': []} >>> s['a']=1 >>> s['a'].append(2) >>> s {'a': [1, 2], 'b': []} >>> s['a']=2 >>> s {'a': [2], 'b': []} >>> s['b']=ComplexDict('c') >>> s {'a': [2], 'b': [{'c': []}]} >>> s.keys() ['a', 'b'] >>> s.values() [[2], [{'c': []}]] >>> s.__list__ [['a', [2]], ['b', [{'c': []}]]]
ข้อเสียคือยังเข้าถึงข้อมูลยาก
>>> s['b'] [{'c': []}] >>> s['b'][0]['c'] [] >>> s['b'][0]['c'] = 5 >>> s['b'][0]['c'] [5] >>> s {'a': [2], 'b': [{'c': [5]}]} >>>
- Printer-friendly version
- Log in or register to post comments
- 3585 reads
Recent comments