Mailing List Archive

Problem with Lists & Index command
Hi All!

I've doing some python programming, and while I'm still learning
I'm getting better every day >g<

But this has me puzzled....

I'm trying to use a list that contains multiple pieces of
information...
Basically a list that contains the equivalent of a "Array"....

And I'm not getting a error, but INDEX doesn't seem to want
to work.... Here's a "test program" made out of a clip from the
program....

import string

entry = 'ABCD'

tcmlist = [('EFGHI',1),('JKLMN',2),('ABCD',3)]
found = 0
entry = string.upper(string.strip(entry))

try:
found = tcmlist.index (entry)
tcmlist[found][1] = tcmlist[found][1] + 1
print 'found'
except ValueError:
tcmlist.append (entry,1)
print 'Sorry could not find it'
else:
pass

print tcmlist

I don't see anything that looks wrong, and getting
no syntax errors, but....

It appears that INDEX doesn't work on a multiple
dimension list????

I've worked around it for now, but it would be sooooo
much neater (for my program code, etc) if it worked..

Suggestions?

- Benjamin
Problem with Lists & Index command [ In reply to ]
Hi Benjamin,

maybe I missed something, but why don't you a dictionary ?

Greetings form Bavaria
Peter
--
---------------------------------------------------------------------------
Dr. Peter Stoehr --- Teisenbergweg 6 --- 85435 Erding --- 08122/47232
---------------------------------------------------------------------------
I'm the terror that flaps through the night
Problem with Lists & Index command [ In reply to ]
> import string
>
> entry = 'ABCD'
>
> tcmlist = [('EFGHI',1),('JKLMN',2),('ABCD',3)]
> found = 0
> entry = string.upper(string.strip(entry))
>
> try:
> found = tcmlist.index (entry)
> tcmlist[found][1] = tcmlist[found][1] + 1
> print 'found'
> except ValueError:
> tcmlist.append (entry,1)
> print 'Sorry could not find it'
> else:
> pass
>
> print tcmlist
>
> I don't see anything that looks wrong, and getting
> no syntax errors, but....
>
> It appears that INDEX doesn't work on a multiple
> dimension list????

Using index() on tcmlist is only going to search through the values in
tcmlist. It won't look inside the tuples that tcmlist contains. So,
you either have to construct a tuple to pass to index, or use a
dictionary instead of a list:

tcmvalues = { 'EFGHI':1,
'JKLMN':2,
'ABCD':3,
}
entry = 'ABCD'
try:
found = tcmvalues[ entry ]
except KeyError:
tcmvalues[ entry ] = 1
else:
pass

This will be much faster than a list lookup anyway, so if you're trying
to count occurances of entries or something similar you should use the
dictionary.

Doug
Problem with Lists & Index command [ In reply to ]
Benjamin Schollnick writes:

> It appears that INDEX doesn't work on a multiple
> dimension list????

Yes, index won't work.

Why? Because the list is a list of tuples,

lst = [("key1", "val1"), ("key2", "val2")...]

so "key1" isn't an element of the list. The tuple ("key1", "val1")
is, however, but to find that you'd need to know the value, which
defeats the purpose.

Basically, the list could have been

lst = [("key1", "val1"), ("key2", "val2"), "key1"]

Here, it seems much more plausible that lst.index("key1") will return
2, not 0. Since list can contain any type, it doesn't automatically
know that it should look inside sublists to find elements.

--
Johann Hibschman johann@physics.berkeley.edu
Problem with Lists & Index command [ In reply to ]
On Fri, 11 Jun 1999 21:22:06, "Dr. Peter Stoehr"
<peter.stoehr@weihenstephan.org> wrote:

> Hi Benjamin,
>
> maybe I missed something, but why don't you a dictionary ?

Because I'm still learning and haven't really read up up on
dictionary's yet....

I'm only about 1/3 (somewhere around pg 150) in the
Python book I have >g< (Out of somewhere around
page 500 or so). And dictionaries haven't been covered
yet....

- Benjamin
Problem with Lists & Index command [ In reply to ]
On Fri, 11 Jun 1999 21:44:47, Doug Hellmann
<doughellmann@mindspring.com> wrote:

> > It appears that INDEX doesn't work on a multiple
> > dimension list????
>
> Using index() on tcmlist is only going to search through the values in
> tcmlist. It won't look inside the tuples that tcmlist contains. So,
> you either have to construct a tuple to pass to index, or use a
> dictionary instead of a list:

Example cut.....to save space...

I'll try this over the weekend...

But, the most obvious question, is.....

Can dictionaries be made & manipulated from
variables?

> tcmvalues = { 'EFGHI':1,
> 'JKLMN':2,
> 'ABCD':3,
> }

i.e.
tcmvalues.append ( entry:entry3)

etc...

Please keep in mind, that I don't know anything about
dictionaries... The book I'm using hasn't hit 'em yet....
(I'm not done reading yet)

- Benjamin
Problem with Lists & Index command [ In reply to ]
On Sat, 12 Jun 1999, Benjamin Schollnick wrote:

> But, the most obvious question, is.....
>
> Can dictionaries be made & manipulated from
> variables?
>
> > tcmvalues = { 'EFGHI':1,
> > 'JKLMN':2,
> > 'ABCD':3,
> > }
>
> i.e.
> tcmvalues.append ( entry:entry3)
>

tcvalues[entry]=entry3



> Please keep in mind, that I don't know anything about
> dictionaries... The book I'm using hasn't hit 'em yet....
> (I'm not done reading yet)


Linear search is usually the slowest algorithm.
That's why they put indexes and tables-of-contents in books,
so they can be accessed non-sequentially! ;-)



---| Steven D. Majewski (804-982-0831) <sdm7g@Virginia.EDU> |---
---| Department of Molecular Physiology and Biological Physics |---
---| University of Virginia Health Sciences Center |---
---| P.O. Box 10011 Charlottesville, VA 22906-0011 |---

"IA-64 looks just about like what you would expect from a PA-RISC
and IA-32 train wreck with a little VLIW thrown in for spice."
* Thomas J. Merritt <tjm@spam.codegen.com> in <news:comp.arch> *
Problem with Lists & Index command [ In reply to ]
On Sat, Jun 12, 1999 at 12:22:19AM +0000, Benjamin Schollnick wrote:
> From: rfreedm1@nospam.rochester.rr.com (Benjamin Schollnick)
> Subject: Re: Problem with Lists & Index command
> To: python-list@python.org
>
> On Fri, 11 Jun 1999 21:22:06, "Dr. Peter Stoehr"
> <peter.stoehr@weihenstephan.org> wrote:
>
> > Hi Benjamin,
> >
> > maybe I missed something, but why don't you a dictionary ?
>
> Because I'm still learning and haven't really read up up on
> dictionary's yet....
>
> I'm only about 1/3 (somewhere around pg 150) in the
> Python book I have >g< (Out of somewhere around
> page 500 or so). And dictionaries haven't been covered
> yet....
>

Which book is that??
I think dictionairies should be in the tutorial!

regards,
Gerrit.

--
The Dutch Linuxgames website. De Nederlandse Linuxgames pagina.
Everything about games on Linux. Alles over spelletjes onder Linux.
Site address: http://linuxgames.nl.linux.org
Personal homepage: http://nl.linux.org/~gerrit/
Problem with Lists & Index command [ In reply to ]
Benjamin Schollnick wrote:
>
> But, the most obvious question, is.....
>
> Can dictionaries be made & manipulated from
> variables?

Of course!

Think of dictionaries as arrays with indexes that can be values other
than numbers. Indeed, dictionaries are sometimes called "associative
arrays" because thinking about them this way makes them easier to
understand.

So, if you have a variable 'entry' with the value "EFGHI" and you want
to use a dictionary to associate the value of another variable entryval
(which is 1) with that value, you could do something like:

entry = 'EFGHI'
entryval = 1
tcmvalues = {} # create an empty dictionary (similar to creating an
emtpy list with [])
tcmvalues[ entry ] = entryval

This creates an association between the "value" in entryval with the
"key" in entry.

Now, suppose you are writing a program to count the number of times a
word occurs in a document. In this case, you would want to increment a
counter stored at the appropriate location. A first try might look
something like this:

wordcounts = {}
for word in document.words():
wordcounts[word] = wordcounts[word] + 1

But what happens when you see a word you've never seen before? On the
right side of the = sign we are retrieving the current value of
wordcounts[word] to add one to it. But if we've never seen the value of
word before, we'll have a problem. Some languages solve this by
returning a null value of some type. Python solves the problem by
raising an exception to let you know you have a situation you need to
deal with.

> Please keep in mind, that I don't know anything about
> dictionaries... The book I'm using hasn't hit 'em yet....
> (I'm not done reading yet)

If you haven't gotten far enough in the book to find a discussion of
dictionaries, you probably haven't seen anything about exception
handling either. Throwing and catching exceptions is (usually) a way to
simplify program logic. It is sort of like saying, "try doing X except
when you encounter a problem. Handle problem type Y like this, handle
problem type Z like this..." The standard library functions and built
in types usually raise exceptions to indicate problems or special
cases. The exception raised by a dictionary when you ask for a value
associated with a key that is not present will be an instance of the
class "KeyError."

The first occurance of a word is a special case, but is not an error.
That means we can just handle the exception and keep going through the
list of words.

wordcounts = {}
for word in document.words():
try:
wordcounts[word] = wordcounts[word] + 1
except KeyError:
wordcounts[word] = 1


Good luck,
Doug
Problem with Lists & Index command [ In reply to ]
Doug Hellmann <doughellmann@mindspring.com> writes:

>
> wordcounts = {}
> for word in document.words():
> try:
> wordcounts[word] = wordcounts[word] + 1
> except KeyError:
> wordcounts[word] = 1

Alternaively, use the `get' method on the dictionary, which will
return a default value if the key is not found. In this case you want
a default value of 0, so the lines become:

wordcounts = {}
for word in documents.words():
wordcounts[word] = wordcounts.get(word,0) + 1

Its not actually any different, just smaller.

--
Tim Evans