comparison lookup_list.py @ 17:759d17112b23

more comments, looping ArrayDataSet iterator, bugfixes to lookup_list, more tests
author bergstrj@iro.umontreal.ca
date Wed, 26 Mar 2008 21:05:14 -0400
parents ff4e551490f1
children 57f4015e2e09
comparison
equal deleted inserted replaced
16:813723310d75 17:759d17112b23
1
2 class LookupList(object):
3 """
4 A LookupList is a sequence whose elements can be named (and unlike
5 a dictionary the order of the elements depends not on their key but
6 on the order given by the user through construction) so that
7 following syntactic constructions work as one would expect:
8 example = Example(['x','y','z'],[1,2,3])
9 example.x = [1, 2, 3] # set or change a field
10 x, y, z = example
11 x = example[0]
12 x = example["x"]
13 print example.keys() # returns ['x','y','z']
14 print example.values() # returns [[1,2,3],2,3]
15 """
16 def __init__(self,names=[],values=[]):
17 assert len(values)==len(names)
18 self.__dict__['_values']=values
19 self.__dict__['_name2index']={}
20 self.__dict__['_names']=names
21 for i in xrange(len(values)):
22 self._name2index[names[i]]=i
23
24 def keys(self):
25 return self._names
26
27 def values(self):
28 return self._values
29
30 def items(self):
31 return zip(self._names,self._values)
32
33 def __getitem__(self,key):
34 """
35 The key in example[key] can either be an integer to index the fields
36 or the name of the field.
37 """
38 if isinstance(key,int):
39 return self._values[key]
40 else: # if not an int, key must be a name
41 return self._values[self._name2index[key]]
42
43 def __setitem__(self,key,value):
44 if isinstance(key,int):
45 self._values[key]=value
46 else: # if not an int, key must be a name
47 if key in self._name2index:
48 self._values[self._name2index[key]]=value
49 else:
50 self._name2index[key]=len(self)
51 self._values.append(value)
52 self._names.append(key)
53
54 def __getattr__(self,name):
55 return self._values[self._name2index[name]]
56
57 def __setattr__(self,name,value):
58 if name in self._name2index:
59 self._values[self._name2index[name]]=value
60 else:
61 self._name2index[name]=len(self)
62 self._values.append(value)
63 self._names.append(name)
64
65 def __len__(self):
66 return len(self._values)
67
68 def __repr__(self):
69 return "{%s}" % ", ".join([str(k) + "=" + repr(v) for k,v in self.items()])