Searching and manipulating lists of tuples

Steve Holden steve at holdenweb.com
Mon Jun 12 15:23:04 CEST 2006


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)]
> 
> I tried to create an algorithm of the following form:
> 
>>>>def algorith(list,str):
> 
> ... 	flag = True
> ... 	for l in list:
> ... 		if l[0] == str:
> ... 			l[1] += 1
> ... 			flag = False
> ... 	if flag:
> ... 		list.append((str,1))
> ...
> 
> 
> But:
> 
> 
>>>>algorith(L,"X")
> 
> 
> gives:
> 
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 5, in algorith
> TypeError: object does not support item assignment
> 
> 
> So clearly that doesn't work... any ideas?
> 
[Nit: try not to use built-in names like "list" and "str" for your own 
purposes, as it stops you from using the bult-ins].

There are many ways you could do this more efficiently. The most 
efficient solution doesn't use a list at all, but a dictionary (the 
following code is untested):

def algorith(d, s):
     if s in d:
         d[s] += 1
     else:
         d[s] = 1

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list