473,769 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Searching and manipulating lists of tuples

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:
def algorith(list,s tr): .... flag = True
.... for l in list:
.... if l[0] == str:
.... l[1] += 1
.... flag = False
.... if flag:
.... list.append((st r,1))
....
But:
algorith(L,"X")


gives:

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 5, in algorith
TypeError: object does not support item assignment
So clearly that doesn't work... any ideas?

Jun 12 '06 #1
7 5881

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
....
So clearly that doesn't work... any ideas?


Yes, use the proper tool for the job. Tuples are immutable (they are
read-only once created). Instead use a dictionary. They key would be
your string, the value would be the count.

Also, don't use 'str' as the name for a string, as it shadows the
built-in 'str' function.

Jun 12 '06 #2

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,s tr): ... flag = True
... for l in list:
... if l[0] == str:
... l[1] += 1
... flag = False
... if flag:
... list.append((st r,1))
...
But:
algorith(L,"X")


gives:

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 5, in algorith
TypeError: object does not support item assignment


Your approach does not work because the tuples in the list a imutable.
The problem occurs in the line l[1] += 1. You could solve the problem
by using lists of lists, rather than lists of tuples. However, if you
only
want to know the frequency of items in the list (i.e. want to build a
histogram)
and you are not interested in the original order of items in the list,
a
dictionary is suited better for this task, because you avoid the linear
time
behavior of:

def histogram(liste ) :
result = {}
for item in liste :
result[item] = result.get(item ,0) + 1
return result.items()

Jun 12 '06 #3
MTD
> Yes, use the proper tool for the job. Tuples are immutable (they are
read-only once created). Instead use a dictionary. They key would be
your string, the value would be the count.


Wow, I really should have thought of that! Thanks.

Jun 12 '06 #4
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,s tr):
... flag = True
... for l in list:
... if l[0] == str:
... l[1] += 1
... flag = False
... if flag:
... list.append((st r,1))
...
But:

algorith(L, "X")

gives:

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve 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

Jun 12 '06 #5

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.ind ex(value)
self._counts[i] += 1
except ValueError:
self._items.app end(value)
self._counts.ap pend(1)

def __getitem__(sel f, index):
return self._items[index], self._counts[index]

def __repr__(self):
return str(zip(self._i tems, self._counts))

m = MyList()

print m
m.append('K')
print m
m.append('K')
print m
m.append('Z')
print m

-----------------------------------

Gerard

Jun 12 '06 #6
Steve Holden <st***@holdenwe b.com> wrote:
def algorith(d, s):
if s in d:
d[s] += 1
else:
d[s] = 1


def algorith(d, s):
d[s] = d.get(s, 0) + 1

And the OP should note that converting between dict d and list of
pairs L is simply a matter of L = d.items() and d = dict(L) (assuming
some other part of the program wants that list representation) .

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Jun 12 '06 #7
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)]
if you don't mind about ordering:

def algorithm(items , target):
d = dict(items)
try:
d[target] += 1
except KeyError:
d[target] = 1
items[:] = d.items()

Now it would probably be better to directly use a dict instead of a list
of tuples if possible...
I tried to create an algorithm of the following form:
def algorith(list,s tr):

Using 'list' and 'str' as identifiers will shadow the eponym builtin
types in this function. This may or may not be a problem here, but it's
usually better to avoid doing so.
... flag = True
... for l in list:
... if l[0] == str:
... l[1] += 1 tuples are immutable. Hence the exception.
... flag = False 'break'ing here would avoid useless iterations. And also allow the use
of the 'else' clause of the for loop, si you don't need a flag. ... if flag:
... list.append((st r,1))
...


While there are pretty good reasons to favor the dict-based solution
(unless you really insist on having sub-optimal code of course !-), the
following is a somewhat more pythonic rewrite of your original code:

def algogo(alist, astring):
for i, (name, count) in enumerate(alist ):
if name == astring:
alist[i] = (name, count+1)
break
else:
alist.append( (astring, 1) )
(snip)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jun 12 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
7053
by: Ivan Voras | last post by:
Are there any performance/size differences between using tuples and using lists? -- -- Every sufficiently advanced magic is indistinguishable from technology - Arthur C Anticlarke
3
2119
by: Thorsten Kampe | last post by:
I found out that I am rarely using tuples and almost always lists because of the more flexible usability of lists (methods, etc.) To my knowledge, the only fundamental difference between tuples and lists is that tuples are immutable, so if this is correct, than list are a superset of tuples, meaning lists can do everything tuples can do and more. Is there any advantage for using tuples? Are they "faster"? Consume less memory? When is...
18
2162
by: Elbert Lev | last post by:
Hi, all! Here is the problem: I have a file, which contains a common dictionary - one word per line (appr. 700KB and 70000 words). I have to read it in memory for future "spell checking" of the words comming from the customer. The file is presorted. So here it goes: lstdict = map(lambda x: x.lower().strip(), file("D:\\CommonDictionary.txt"))
3
1866
by: Nickolay Kolev | last post by:
Hi all, Continuing the search for interesting challenges with lists, tuples and dictionaries I am looking for a way to do the following. one = { 'a' : 1, 'b' : 2, 'c' : 3 }
24
3967
by: Lasse Vågsæther Karlsen | last post by:
I need to merge several sources of values into one stream of values. All of the sources are sorted already and I need to retrieve the values from them all in sorted order. In other words: s1 = s2 = s3 = for value in ???(s1, s2, s3):
4
1802
by: Peter Notebaert | last post by:
I am new to Python and have to create an import library in C that uses matrices. These matrices can be one-dimensional (vectors) or two-dimensional. If I look in the ActivePython 2.4 documentation at data structures, then I see at least 2 posibilities to represent them: Lists and Tuples. The documention doesn't give me much information on what the best choice is for the data type to provide/return these matrices.
122
5526
by: C.L. | last post by:
I was looking for a function or method that would return the index to the first matching element in a list. Coming from a C++ STL background, I thought it might be called "find". My first stop was the Sequence Types page of the Library Reference (http://docs.python.org/lib/typesseq.html); it wasn't there. A search of the Library Reference's index seemed to confirm that the function did not exist. A little later I realized it might be called...
27
1683
by: seberino | last post by:
Please help me think of an example where immutable tuples are essential. It seems that everywhere a tuple is used one could just as easily use a list instead. chris
25
4099
by: beginner | last post by:
Hi, I am wondering how do I 'flatten' a list or a tuple? For example, I'd like to transform or ] to . Another question is how do I pass a tuple or list of all the aurgements of a function to the function. For example, I have all the arguments of a function in a tuple a=(1,2,3). Then I want to pass each item in the tuple to a function f so that I make a function call f(1,2,3). In perl it is a given, but in python, I haven't figured out
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.