M
MTD
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:.... flag = True
.... for l in list:
.... if l[0] == str:
.... l[1] += 1
.... flag = False
.... if flag:
.... list.append((str,1))
....
But:
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?
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:.... flag = True
.... for l in list:
.... if l[0] == str:
.... l[1] += 1
.... flag = False
.... if flag:
.... list.append((str,1))
....
But:
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?