MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs > > e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs > twice > > If I am given a string, I want to search L to see if it occurs already. > If it does, I find the corresponding tuple and increment the integer > part. If not, I append the new element with int = 1. > > e.g. > > algorithm(L, "X") would produce output L = [("X",2),("Y",2)] > algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] >
just a thought: class MyList(object): def __init__(self): self._items = [] self._counts = [] def append(self, value): try: i = self._items.index(value) self._counts[i] += 1 except ValueError: self._items.append(value) self._counts.append(1) def __getitem__(self, index): return self._items[index], self._counts[index] def __repr__(self): return str(zip(self._items, self._counts)) m = MyList() print m m.append('K') print m m.append('K') print m m.append('Z') print m ----------------------------------- Gerard -- http://mail.python.org/mailman/listinfo/python-list